Metadata-Version: 2.4
Name: msp-py
Version: 0.1.0a2
Summary: Model Sensing Protocol — a node-centric paradigm for decentralized AI communication.
Author: hxh230802
License-Expression: MIT
Project-URL: Homepage, https://git.tsinghua.edu.cn/modelsensingprotocol/modelsensingprotocol
Project-URL: Repository, https://git.tsinghua.edu.cn/modelsensingprotocol/modelsensingprotocol
Project-URL: Issues, https://git.tsinghua.edu.cn/modelsensingprotocol/modelsensingprotocol/-/issues
Project-URL: Changelog, https://git.tsinghua.edu.cn/modelsensingprotocol/modelsensingprotocol/-/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

<p align="center">
  <img src="assets/banner.png" alt="MSP — Model Sensing Protocol: every local app is a neighbour, not a socket">
</p>

<p align="center">
  <a href="README.md">English</a> | <a href="README.zh-CN.md">简体中文</a>
</p>

<p align="center">
  <a href="https://pypi.org/project/msp-py/"><img src="https://img.shields.io/pypi/v/msp-py?label=pypi&color=0a66e4" alt="PyPI"></a>
  <a href="https://pypi.org/project/msp-py/"><img src="https://img.shields.io/pypi/pyversions/msp-py?label=python" alt="Python versions"></a>
  <img src="https://img.shields.io/badge/license-MIT-blue" alt="License: MIT">
  <img src="https://img.shields.io/badge/tests-272%20passed-brightgreen" alt="Tests">
  <img src="https://img.shields.io/badge/status-alpha-orange" alt="Status: alpha">
  <br>
  <a href="docs/POSITIONING.md"><img src="https://img.shields.io/badge/why-MSP%20%E2%89%A0%20MCP-0a66e4" alt="Why MSP, not MCP"></a>
  <a href="docs/DESIGN.md"><img src="https://img.shields.io/badge/design-decisions-0a66e4" alt="Design decisions"></a>
  <a href="docs/whitepaper.md"><img src="https://img.shields.io/badge/paper-whitepaper-0a66e4" alt="Whitepaper"></a>
  <a href="https://github.com/ModelSensingProtocol/msp-ts"><img src="https://img.shields.io/badge/impl-TypeScript-3178c6" alt="TypeScript implementation"></a>
  <a href="docs/wiki/README.md"><img src="https://img.shields.io/badge/docs-wiki-0a66e4" alt="Wiki"></a>
  <a href="https://github.com/hxh230802/dsh-msp"><img src="https://img.shields.io/badge/agent-DeepSeek%20Harness-0a66e4" alt="DeepSeek Harness plugin"></a>
</p>

**MSP turns local software into neighbours that speak up.** A node announces itself with a lease, so
presence is a fact you can read rather than a config you maintain; it can push when something happens,
and nodes can serve each other directly instead of routing every step through a model.

New here? Start with the **[wiki](docs/wiki/README.md)** — five minutes to two nodes calling each other.

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

## 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"

## Implementations

MSP is a wire format, not a library — any language can host a node. These are the ones that speak
the same bytes:

| Language | Repository | State |
|---|---|---|
| **Python** (reference) | this repository · [PyPI `msp-py`](https://pypi.org/project/msp-py/) | 0.1.0a1; the semantics every other implementation is measured against |
| **C++** | [`ModelSensingProtocol/msp-cpp`](https://github.com/ModelSensingProtocol/msp-cpp) *(private)* | CMake project with CI, unit tests and an interop harness |
| **.NET** | [`ModelSensingProtocol/msp-dotnet`](https://github.com/ModelSensingProtocol/msp-dotnet) *(private)* | `Msp.slnx` solution, samples and tests; NuGet package id in place |
| **TypeScript** | [`ModelSensingProtocol/msp-ts`](https://github.com/ModelSensingProtocol/msp-ts) | zero dependencies, Node ≥ 22.6, byte-level interop with `msp-py` |
| **Agent integration** | [`hxh230802/dsh-msp`](https://github.com/hxh230802/dsh-msp) | DeepSeek Harness plugin: every MSP node's tools become callable, long tasks included |

The `dev/cpp` branch in this repository is superseded by `msp-cpp` (same tip, `46cdcfe`).

> Two of the repositories above are private. While they stay private, the links only resolve for
> people with access — worth deciding before this repository itself is made public.

## Positioning: neighbours, not sockets

MCP and MSP are not the same kind of thing:

| | MCP | MSP |
|---|---|---|
| Topology | hub-and-spoke: the model is the centre, every server attaches to it | mesh: nodes are peers, the agent is just one of them |
| Direction | pull-dominant: the model asks | pull **and push**: an app can broadcast when something happens |
| Presence | one entry in a config file | leases: what is running right now is a fact you can read |
| Lifetime | one call, one session | long-lived connection + heartbeat + multi-round / task semantics |
| App-to-app | must go through the model | direct (A's capability can serve B) |

So for the vision "every piece of local software can interact with AI", MCP has the wrong shape: it
assumes software is a pile of passive tools, whereas what we want is a pile of **stateful neighbours
that speak up and know each other**. Wrapping MCP in a shim is not merely complex — it compresses a
mesh into a hub and throws away push and presence, the two things actually worth having.

Full argument (the single most painful example, costs, stdio vs streamable HTTP, and the "one protocol
at runtime, MCP only at import time" boundary): [`docs/POSITIONING.md`](docs/POSITIONING.md) ·
[中文](docs/POSITIONING.zh-CN.md).

## 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.

### Tools vs skills

A `ToolDescriptor` answers **what a node can do**: one step, described by `inputSchema`, checkable by
a schema. It does not answer **how to use it well** — which of several tools to pick, in what order,
what to do when one fails, what "done" looks like. That knowledge belongs to no single tool, and
cramming it into every tool's `description` is how a twenty-tool catalog turns into a 120k-token
instruction sheet.

MSP gives that knowledge its own slot: `Manifest.skills`, a one-line index whose `whenToUse` lets a
caller decide whether the full procedure is worth fetching (`skill_get` → `skill_content`, planned).

| | tools | skills |
|---|---|---|
| Answers | what can be done | how to do it properly |
| Shape | declarative, one step, stateless | procedural, multi-step, carries judgement |
| Machine-checkable | structure (`inputSchema`) | **references** — every `toolsUsed` must exist in `tools` |
| Who decides when | the caller guesses | `whenToUse` says so |

```python
from msp import MSPNode, SkillDescriptor

node = MSPNode("demo")
node.manifest.add_skill(SkillDescriptor(
    name="triage",
    summary="Find out why a peer stopped answering",
    when_to_use="A call failed and the error text does not say why",
    tools_used=["read_file", "tail_log"],      # must be tools this node really exposes
))

node.manifest.lint_skills()      # non-empty: one problem per unresolved tool reference

@node.tool("read_file")
def read_file(path: str) -> str: ...

@node.tool("tail_log")
def tail_log(path: str, lines: int = 50) -> str: ...

node.manifest.lint_skills()      # [] — every reference now resolves
```

`lint_skills()` is the point of the design. The body is prose and no schema can validate it, but
**its references can be**: a skill naming a tool the node does not expose goes red at build time
instead of failing silently at call time.

> **Skills are untrusted data.** A skill body lands in the caller's *model context*, not in an
> executor — and it arrives with the authority of "this is how you do it". It must never widen
> authorization, never override the host's goal, and never be executed as a system instruction.
> See [the spec](docs/spec/capabilities.md#8-安全考量).

### 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")  # add a discovery source at runtime
```

### 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.

### A2A mode (`msp/a2a`): native interop, no adapter in the loop

`msp/task` ports A2A's *task semantics*; `msp/a2a` goes further and maps
A2A v1.0's **object model and eleven operations** directly onto MSP
signals — reusing the existing transports, discovery, and grant table.
No HTTP, no JSON-RPC. The JSON-RPC / gRPC / HTTP+JSON bindings the
official A2A ecosystem expects are an *adapter*, deliberately kept
separate from this mode.

```python
agent = MSPNode("agent", preset=Preset.A2A_PEER)   # or register_pattern("msp/a2a")

@agent.a2a.skill("report", description="Write a report about a topic")
def report(ctx, topic: str) -> str:
    ctx.status("working", "drafting")
    ctx.add_text(f"Report on {topic} …")           # an Artifact
    return "done"

task = client.a2a.send_message("agent", "Q3 revenue", skill_id="report")
task.status.state                                   # TASK_STATE_COMPLETED
client.a2a.list_tasks("agent", context_id=task.context_id)
```

The Agent Card is projected into `Manifest.pattern_metadata["msp/a2a"]`
automatically and can be read with `client.a2a.remote_agent_card("agent")`.
Full contract: [docs/spec/patterns/a2a.md](docs/spec/patterns/a2a.md).

## 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 .
```

Editable install: source changes take effect immediately (a virtual environment is recommended).

## Run

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

## Run tests

The suite is plain-stdlib `unittest` and mocks nothing: real sockets, real subprocesses. Two ways
to run it, pick one.

After `pip install -e .`, from the repository root:

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

Without installing, point `PYTHONPATH` at `src`:

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

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

A single module works too, for example `python -m unittest tests.test_task`.

Note: Windows has no `AF_UNIX`, so the four UDS cases in `tests/test_uds.py` are skipped
automatically — they are not failures.

## Acknowledgement

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