Metadata-Version: 2.4
Name: msp-py
Version: 0.1.0a1
Summary: Model Sensing Protocol — a node-centric paradigm for decentralized AI communication.
Author: hxh230802
License-Expression: MIT
Project-URL: Homepage, https://github.com/hxh230802/MSP
Project-URL: Repository, https://github.com/hxh230802/MSP
Project-URL: Issues, https://github.com/hxh230802/MSP/issues
Project-URL: Changelog, https://github.com/hxh230802/MSP/blob/master/CHANGELOG.md
Keywords: ai,protocol,signal,mcp,decentralized,multi-agent
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: watchdog<7,>=4.0
Provides-Extra: dev
Requires-Dist: PyYAML>=6; extra == "dev"
Requires-Dist: jsonschema>=4; extra == "dev"
Dynamic: license-file

# MSP — Model Sensing Protocol

A node-centric paradigm for decentralized AI communication.

Everything is a node.
Everything is a signal.
Every layer is extensible.

[中文](README.zh-CN.md)

## Status

Early prototype. Core layers implemented:

- `core/`       Signal, Manifest, ContentBlock, Preset, MSPNode
- `discovery/`  Shared-directory discovery
- `presence/`   Shared-directory advertisement
- `transport/`  TCP backend with pluggable registry
- `protocol/`   Handshake, broadcast, reqid-based tool calling
- `patterns/`   Pluggable patterns (multi-round)
- `mcp/`        MCP interop adapter (stdio, tools) — realizing "MCP ⊆ MSP"

## Architecture

> The normative specification lives in [docs/spec/](docs/spec/README.md); design rationale in [docs/DESIGN.md](docs/DESIGN.md); the problem statement and positioning in [docs/whitepaper.md](docs/whitepaper.md).

```text
╔══════════════════════════════════════════════════════════════════════════╗
║                         MSP Overall Architecture                         ║
║                          Model Sensing Protocol                          ║
║                                                                          ║
║   Everything is a node.  Everything is a signal.                         ║
╚══════════════════════════════════════════════════════════════════════════╝

┌──────────────────────────────────────────────────────────────────────────┐
│                            Application Layer                             │
│  ┌────────────────────────────────────────────────────────────────────┐  │
│  │  MSPNode                                                           │  │
│  │                                                                    │  │
│  │  @node.tool("name")       declare a tool                           │  │
│  │  @node.signal_source(p)   declare a signal-source generator        │  │
│  │  node.declare_signal(p)   declare a signal path (no emission)      │  │
│  │  @node.on(path)           register a signal callback               │  │
│  │  node.publish(p, d)       publish a signal manually                │  │
│  │  node.ensure_connected(p)  dial a peer on demand (lazy policy)     │  │
│  │  node.settle(t)            wait for in-flight dials to land        │  │
│  │  node.call(peer, t, a)    call a tool synchronously                │  │
│  │  node.register_pattern(h) register a communication pattern         │  │
│  └────────────────────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌──────────────────────────────────────────────────────────────────────────┐
│                              Pattern Layer                               │
│  ┌────────────────────────────────────────────────────────────────────┐  │
│  │                 PatternHandler abstract base class                 │  │
│  │  pattern_id · fallback_to · conflicts_with                         │  │
│  │  on_signal(protocol, peer_id, sig)                                 │  │
│  └────────────────────────────────────────────────────────────────────┘  │
│                                                                          │
│  ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ ┌──────────────┐  │
│  │ Request-Reply │ │ PubSub        │ │ MultiRound    │ │ Streaming    │  │
│  │ (core pattern)│ │ (core pattern)│ │ (this round)  │ │ (future)     │  │
│  │               │ │               │ │               │ │              │  │
│  │ tool_call     │ │ signal        │ │ tool_call     │ │ stream_start │  │
│  │ tool_result   │ │               │ │ tool_result   │ │ stream_chunk │  │
│  │               │ │               │ │ input_required│ │ stream_end   │  │
│  │               │ │               │ │ input_response│ │              │  │
│  └───────────────┘ └───────────────┘ └───────────────┘ └──────────────┘  │
│                                                                          │
│  ┌───────────────┐ ┌───────────────┐ ┌───────────────┐                   │
│  │ TaskLifecycle │ │ CallbackPush  │ │ AsyncPolling  │                   │
│  │ (future)      │ │ (future)      │ │ (future)      │                   │
│  └───────────────┘ └───────────────┘ └───────────────┘                   │
│   ... (future extension)                                                 │
│                                                                          │
│   Pluggable · standalone files · keeps the core clean                    │
└──────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌──────────────────────────────────────────────────────────────────────────┐
│                              Protocol Layer                              │
│   MSPProtocol                                                            │
│  ┌────────────────────────────────────────────────────────────────────┐  │
│  │  Core signals (handled by the protocol layer)                      │  │
│  │  HELLO · ACK · PING · PONG · ERROR                                 │  │
│  └────────────────────────────────────────────────────────────────────┘  │
│  ┌────────────────────────────────────────────────────────────────────┐  │
│  │  Signal routing                                                    │  │
│  │  _dispatch(peer_id, sig)                                           │  │
│  │  if sig.pattern: → patterns[sig.pattern].on_signal(...)            │  │
│  │  else:           → _dispatch_core(...)                             │  │
│  └────────────────────────────────────────────────────────────────────┘  │
│  ┌────────────────────────────────────────────────────────────────────┐  │
│  │  Connection management                                             │  │
│  │  connections · peer_manifests · pending_calls                      │  │
│  │  handlers · _on_connected · _on_disconnected                       │  │
│  └────────────────────────────────────────────────────────────────────┘  │
│  ┌────────────────────────────────────────────────────────────────────┐  │
│  │  Encoding                                                          │  │
│  │  _encode(Signal) → bytes · _decode(bytes) → dict                   │  │
│  └────────────────────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌──────────────────────────────────────────────────────────────────────────┐
│                             Transport Layer                              │
│  ┌────────────────────────────────────────────────────────────────────┐  │
│  │  TransportRegistry                                                 │  │
│  │  register(type, transport) · connect(endpoint) · listen_all()      │  │
│  └────────────────────────────────────────────────────────────────────┘  │
│                                                                          │
│  ┌────────────────────┐ ┌────────────────────┐ ┌────────────────────┐    │
│  │ TCPTransport       │ │ WebSocketTransport │ │ QUICTransport      │    │
│  │ (implemented)      │ │ (implemented)       │ │ (future)           │    │
│  │                    │ │                    │ │                    │    │
│  │ length-prefix frame│ │ native msg framing │ │ stream framing     │    │
│  │ send/recv          │ │ send/recv          │ │ send/recv          │    │
│  └────────────────────┘ └────────────────────┘ └────────────────────┘    │
│                                                                          │
│   Unified interface: Connection.send(bytes) / receive() -> bytes         │
│   Only moves bytes · no message semantics                                │
└──────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌──────────────────────────────────────────────────────────────────────────┐
│                           Discovery / Presence                           │
│                                                                          │
│  ┌──────────────────────────────┐  ┌──────────────────────────────┐      │
│  │          Discovery           │  │           Presence           │      │
│  │     (how to find others)     │  │      (how to be found)       │      │
│  │                              │  │                              │      │
│  │  ┌──────────────────────┐    │  │  ┌──────────────────────┐    │      │
│  │  │  DirectoryScan       │    │  │  │  DirectoryWrite      │    │      │
│  │  │  shared-dir scan     │    │  │  │  shared-dir write    │    │      │
│  │  │  (implemented)       │    │  │  │  (implemented)       │    │      │
│  │  └──────────────────────┘    │  │  └──────────────────────┘    │      │
│  │  ┌──────────────────────┐    │  │  ┌──────────────────────┐    │      │
│  │  │  ManualConnect       │    │  │  │  ManualAdvertise     │    │      │
│  │  │  manual address      │    │  │  │  manual advertise    │    │      │
│  │  │  (implemented)        │    │  │  │  (implemented)        │    │      │
│  │  └──────────────────────┘    │  │  └──────────────────────┘    │      │
│  │  ┌──────────────────────┐    │  │  ┌──────────────────────┐    │      │
│  │  │  DHTDiscovery        │    │  │  │  DHTAdvertise        │    │      │
│  │  │  DHT lookup          │    │  │  │  DHT register        │    │      │
│  │  │  (future)            │    │  │  │  (future)            │    │      │
│  │  └──────────────────────┘    │  │  └──────────────────────┘    │      │
│  └──────────────────────────────┘  └──────────────────────────────┘      │
│                                                                          │
│   Orthogonal · freely composable                                         │
│   Unified contract: Endpoint = { transport_type, address, node_id }      │
└──────────────────────────────────────────────────────────────────────────┘

═══════════════════════════════════════════════════════════════════════════
                             Data flow examples                            
═══════════════════════════════════════════════════════════════════════════

Scenario 1: Tool call (request-reply pattern)

  Client                                   Server
    │                                        │
    │  1. User: client.call(peer, tool, args)
    │         │
    │         ▼
    │  2. Pattern layer RequestReplyHandler
    │         creates the tool_call signal
    │         │
    │         ▼
    │  3. Protocol layer _encode → JSON bytes
    │         │
    │         ▼
    │  4. Transport layer TCP + 4-byte length prefix
    │         │
    │─────────┼─────────────────────────────►│
    │                                        │  5. Transport layer reads
    │                                        │
    │                                        │  6. Protocol layer _decode
    │                                        │
    │                                        │  7. Pattern layer dispatches
    │                                        │     runs the tool function
    │                                        │
    │◄────────┼─────────────────────────────│  8. returns tool_result
    │         │                              │
    │  9. wakes the waiting call()            │
    │         │                              │
    │  10. returns ToolResult                 │
    ▼                                        ▼

Scenario 2: Signal push (broadcast)

  Publisher                                Subscriber
    │                                        │
    │  1. Generator yields {"status": "thinking"}
    │         │
    │         ▼
    │  2. Node auto-publishes ("ai.state", payload)
    │         │
    │         ▼
    │  3. Broadcasts the signal to every connected peer
    │─────────┼─────────────────────────────►│
    │                                        │  4. Receives the signal
    │                                        │
    │                                        │  5. Filters locally: path matches
    │                                        │     "ai.state" → triggers
    │                                        │     @on("ai.state") callback
    ▼                                        ▼

Scenario 3: Multi-round (MultiRound pattern)

  Client                                   Server
    │                                        │
    │  ── tool_call(reqid=1) ──────────────►│
    │                                        │  Tool running, missing arg
    │  ◄── input_required(reqid=1) ─────────│  "Departure date?"
    │                                        │
    │  (client calls input_fn for the answer) │
    │                                        │
    │  ── input_response(reqid=1) ─────────►│  "2026-10-15"
    │                                        │  Tool continues
    │                                        │
    │  ◄── input_required(reqid=1) ─────────│  "Preferred airline?"
    │  ── input_response(reqid=1) ─────────►│  "Air China"
    │                                        │  Tool completes
    │  ◄── tool_result(reqid=1) ────────────│  Final result
    ▼                                        ▼

═══════════════════════════════════════════════════════════════════════════
                            Core data structures                           
═══════════════════════════════════════════════════════════════════════════

┌─────────────────────────────────────────────────────────────────────────┐
│  Signal                                                                 │
│  ┌───────────────────────────────────────────────────────────────────┐  │
│  │  type:      "tool_call" | "signal" | "hello" | ...                │  │
│  │  source:    "node_a"                                              │  │
│  │  pattern:   "msp/multi-round" | None  ← routing key               │  │
│  │  target:    "node_b" | None                                       │  │
│  │  path:      "ai.state" | None            ← for pub-sub            │  │
│  │  reqid:     "mr-1" | None                ← for request-reply      │  │
│  │  payload:   {...}                                                 │  │
│  │  timestamp: 1712345678.123                                        │  │
│  └───────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────┐
│  Manifest (node capability list)                                        │
│  ┌───────────────────────────────────────────────────────────────────┐  │
│  │  version:           3                                             │  │
│  │  patterns:          ["msp/request-reply", "msp/pubsub",           │  │
│  │                      "msp/multi-round"]                           │  │
│  │  signals:           {path: SignalDescriptor}                      │  │
│  │  tools:             {name: ToolDescriptor}                        │  │
│  │  resources:         {uri: ResourceDescriptor}                     │  │
│  │  prompts:           {name: PromptDescriptor}                      │  │
│  │  clientCapabilities: {sampling, elicitation, roots}               │  │
│  └───────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────┐
│  Endpoint (node transport endpoint)                                     │
│  ┌───────────────────────────────────────────────────────────────────┐  │
│  │  transport_type:  "tcp" | "websocket" | "quic"                    │  │
│  │  address:         {"host": "127.0.0.1", "port": 45678}            │  │
│  │  node_id:         "node_a"                                        │  │
│  └───────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────┘

═══════════════════════════════════════════════════════════════════════════
                               MCP comparison                              
═══════════════════════════════════════════════════════════════════════════

  ┌──────────────────────────┬─────────────────────────────────────────┐
  │           MCP            │                   MSP                   │
  ├──────────────────────────┼─────────────────────────────────────────┤
  │ Client-Host-Server       │ Peer-to-peer nodes                      │
  │ Manual server config     │ Auto-discovery                          │
  │ Request-reply            │ Request-reply + pub-sub + multi-round + ...│
  │ Request/response + notif.│ Full-duplex                             │
  │ Protocol-level ext. (SEP)│ Pluggable patterns (PatternHandler)     │
  │ Large core changes       │ Core changes ≤ 60 lines                 │
  │ Tool-centric             │ Node-centric                            │
  │ Everything is a tool     │ Everything is a node                    │
  └──────────────────────────┴─────────────────────────────────────────┘

  ┌───────────────────────────────────────────────────────────────────┐
  │                                                                   │
  │                             MCP ⊆ MSP                             │
  │                                                                   │
  │      MCP is a special case of MSP in the "tool call" scenario     │
  │                                                                   │
  └───────────────────────────────────────────────────────────────────┘
```

### Startup timing: `start(settle=...)`

`start()` blocks until the network has settled — at most `settle_timeout`
(500 ms by default):

```python
node.start()                          # settle=True by default: peers are connected on return
ok = node.start(settle_timeout=1.0)   # custom bound; False means dials were still in flight
node.start(settle=False)              # purely non-blocking: connections form in background

node.settle(0.5)                      # or wait separately; returns whether it settled in time
```

Why it exists: **discovery is synchronous, dialing is asynchronous.** The
directory scan runs inside `start()` (neighbors land in the neighbor table
immediately), but dials happen on background threads. So a `publish()` right
after `start()` fans out to an empty connection set — **silently dropped, no
error**. `settle` collapses that window.

Boundaries (honest version):

- **Waits, never initiates**: `settle()` never calls `ensure_connected()`. On a
  `connect_policy="lazy"` node it is a no-op — it returns `True` immediately and
  **never connects a peer that lazy chose not to connect**.
- Covers **discovery-driven** dials only; connections started by `call()` /
  `fetch_manifest()` / `msp/task` are not counted.
- Does not promise "every future node is connected": nodes that announce after
  `start()` returned go through normal discovery.
- A timeout is a bound, not an error: `False` only means some dial had not
  landed yet, and the node keeps working.

### Peer view

A peer's information is spread across several places — its `Endpoint`
(on the node), and its `Connection` and manifest (on the protocol
layer). `Peer` aggregates them into one read-only object.

`Peer` is a *view*, not a *store*: it holds no state, and every
attribute reads live from the owning node. When a peer updates its
manifest or drops the connection, the same `Peer` object reflects it
immediately — no copy to keep in sync.

```python
peer = node.peer("node_a")
peer.is_connected                      # bool
peer.manifest                          # dict | None
peer.tools()                           # ["get_weather", ...]
peer.signals()                         # ["ai.state", ...]
peer.supports("msp/multi-round")       # bool

for p in node.connected_peers():
    if p.supports("msp/multi-round"):
        ...
```

Operations (`call`, `publish`) stay on the node — `Peer`
is query-only. `publish` is a broadcast, not peer-scoped, so it does
not belong on `Peer`.

### Calling a peer's tools

`inputSchema` travels in the manifest, so a peer's tools can be turned
into local callables — no code-generation step, and nothing new on the wire:

```python
peer = node.peer("node_a")

peer.t.get_weather(location="Beijing")            # -> ToolResult
peer.t.get_weather(location="Beijing").unwrap()   # -> {'temp': 22, ...}; raises on error
peer.t["get_weather"](location="Beijing")         # dynamic / dotted names
peer.t.tool("tools")                              # escape hatch for collisions

print(peer.t.signature("get_weather"))   # (location: str, *, days: int = <optional>)
print(peer.t.describe("get_weather"))    # description + per-argument docs
peer.t.names()                           # what the peer declares
peer.t.conflicts()                       # names not reachable as attributes
```

`<optional>` is not a placeholder for "no such thing": it means the schema marks
the argument optional but declares **no default**, so omitting it sends nothing
and the provider applies its own default. (`schema_from_func` never emits
`default`, which is why a Python default of `3` shows up as `<optional>` rather
than `3` — see the DESIGN notes for why we degrade instead of guessing.)

Three properties are deliberate:

- **No shadowing.** Tools live under `peer.t`, not on `Peer` itself. `Peer`
  already has `tools` / `signals` / `manifest` / `node_id`, and tool names may
  collide with them; `__getattr__` never fires for an existing attribute, so
  hanging tools directly on `Peer` would silently return the wrong thing.
  Colliding tools stay reachable through `peer.t["..."]` / `peer.t.tool(...)`.
- **Attribute access is pure.** `peer.t.anything` does not dial, does not read
  the manifest, and keeps no state; `ensure_connected()` happens when you
  *call*. Otherwise `hasattr`, `dir`, or a debugger expanding the object would
  trigger network I/O — and `Peer` promises benign, side-effect-free queries.
- **Errors stay values.** A call returns `ToolResult`; use `.unwrap()` when you
  want an exception. Wrong arguments are a caller-side programming error, so
  they raise `TypeError` locally instead of becoming a remote error string.

Signature quality is bounded by `schema_from_func`, which currently emits no
`default` and silently drops pydantic v2 constraints; anything the schema does
not express degrades to `Any` rather than being guessed. Return values are
still `Any`, because `ToolDescriptor.outputTypes` is always empty today.

### Extension hooks (install_api)

A layer component may define `install_api(node)`; MSPNode calls it (if
present) right after constructing the component, so the component can
attach convenience methods onto the node without changing the core.
Patterns use it for `node.multiround`; manual discovery uses it for
`node.add_manual_source(...)`.

```python
node.start()
node.add_manual_source("http://registry2:8080/nodes")  # 运行时动态加发现源
```

### MCP interop (adapter)

`msp.mcp` turns the "MCP ⊆ MSP" box above into working code: in the
tool-call scenario, an MSP node bridges the MCP ecosystem in both
directions — without touching the core.

- `MCPClient` — MSP acts as an MCP client, calling an MCP server directly
- `MCPServer` — expose an MSP node as an MCP server
- `mount_mcp_tools` — re-export a remote MCP server's tools as MSP tools

```python
from msp.mcp import MCPClient, spawn, mount_mcp_tools

# MSP → MCP: call a local MCP server (spawned over stdio)
client = MCPClient(spawn(["npx", "-y", "@modelcontextprotocol/server-filesystem"]))
print(client.list_tools())
print(client.call_tool("read_file", {"path": "/tmp/a.txt"}))

# Bridge: mount that MCP server's tools on this node so other MSP peers can call them
node_a = MSPNode("node_a")
mount_mcp_tools(node_a, client)
node_b.call("node_a", "read_file", {"path": "/tmp/a.txt"})

# MCP → MSP: run node as an MCP server; an external MCP client spawns this process
#   from msp.mcp import MCPServer, current_stdio
#   MCPServer(node, current_stdio()).run()
```

Current scope: stdio transport + tools capability (`initialize` /
`tools/list` / `tools/call`). Streamable HTTP and resources / prompts /
sampling come later.

## ProReAct: waiting is a subscription, not an action

The classic ReAct loop is pull-based and turn-based: observation only
comes from tool returns, so "waiting" — a non-action — can only be faked
as an action. To wait for a download, a push, or a job, the agent can
only `sleep(45)` and check again; if not done, sleep and check again.
Polling is not a strategy here — it is a forced expression: the model
writes "not acting" as "acting", spending tokens and turns on "nothing
happened yet".

MSP moves "waiting" out of the loop and into the protocol layer:

```python
@node.on("notify.web.download")   # declare interest locally, then suspend
def on_done(sig):
    # when the download truly finishes, the peer publishes the path,
    # the broadcast reaches this node, and the event wakes the agent
    ...
```

Waiting is downgraded from an "action" to a "subscription" — declaring
interest locally instead of polling — and wake-up is passive. That is
exactly what "Sensing" in the protocol's name means: the protocol senses,
so the model doesn't have to poll.

## Install

```bash
pip install -e .
```

以「可编辑」模式安装，源码改动即时生效（建议在虚拟环境里执行）。

## Run

```bash
python -m msp.core.node
```

## Run tests（运行测试）

测试是纯标准库 `unittest`（不 mock 网络：真 socket、真子进程），两种跑法任选其一。

装过包（`pip install -e .`）之后，直接在仓库根目录跑：

```bash
python -m unittest discover -s tests
```

不想安装、只想用源码树时，给 `PYTHONPATH` 指向 `src`：

```bash
# Linux / macOS
PYTHONPATH=src python -m unittest discover -s tests

# Windows PowerShell
$env:PYTHONPATH="src"; python -m unittest discover -s tests
```

也可以只跑单个文件，例如 `python -m unittest tests.test_task`。

注意：Windows 没有 `AF_UNIX`，`tests/test_uds.py` 里的 4 个 UDS 用例会自动
skip（不是失败）。

## Acknowledgement

Thanks to Cordis, DSH, KnotLink, MCP and Glycoprotein.
