This release is a pre-release and may not be stable for production use.
MSP — Model Sensing Protocol
A node-centric paradigm for decentralized AI communication.
Everything is a node. Everything is a signal. Every layer is extensible.
Status
Early prototype. Core layers implemented:
core/Signal, Manifest, ContentBlock, Preset, MSPNodediscovery/Shared-directory discoverypresence/Shared-directory advertisementtransport/TCP backend with pluggable registryprotocol/Handshake, broadcast, reqid-based tool callingpatterns/Pluggable patterns (multi-round)mcp/MCP interop adapter (stdio, tools) — realizing "MCP ⊆ MSP"
Architecture
The normative specification lives in docs/spec/; design rationale in docs/DESIGN.md; the problem statement and positioning in docs/whitepaper.md.
╔══════════════════════════════════════════════════════════════════════════╗
║ 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):
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 callsensure_connected(). On aconnect_policy="lazy"node it is a no-op — it returnsTrueimmediately and never connects a peer that lazy chose not to connect. - Covers discovery-driven dials only; connections started by
call()/fetch_manifest()/msp/taskare 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:
Falseonly 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.
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:
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 onPeeritself.Peeralready hastools/signals/manifest/node_id, and tool names may collide with them;__getattr__never fires for an existing attribute, so hanging tools directly onPeerwould silently return the wrong thing. Colliding tools stay reachable throughpeer.t["..."]/peer.t.tool(...). - Attribute access is pure.
peer.t.anythingdoes not dial, does not read the manifest, and keeps no state;ensure_connected()happens when you call. Otherwisehasattr,dir, or a debugger expanding the object would trigger network I/O — andPeerpromises 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 raiseTypeErrorlocally 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(...).
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 directlyMCPServer— expose an MSP node as an MCP servermount_mcp_tools— re-export a remote MCP server's tools as MSP tools
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:
@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
pip install -e .
以「可编辑」模式安装,源码改动即时生效(建议在虚拟环境里执行)。
Run
python -m msp.core.node
Run tests(运行测试)
测试是纯标准库 unittest(不 mock 网络:真 socket、真子进程),两种跑法任选其一。
装过包(pip install -e .)之后,直接在仓库根目录跑:
python -m unittest discover -s tests
不想安装、只想用源码树时,给 PYTHONPATH 指向 src:
# 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.
Metadata
Release files for msp-py 0.1.0a1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| msp_py-0.1.0a1.tar.gz | 215.0 kB | Without provenance | Details for msp_py-0.1.0a1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| msp_py-0.1.0a1-py3-none-any.whl | Python 3 | none | any | Details for msp_py-0.1.0a1-py3-none-any.whl |
Total release size: 372.9 kB
Release files / msp_py-0.1.0a1.tar.gz
| Download URL | msp_py-0.1.0a1.tar.gz |
|---|---|
| Size | 215.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
435d6f22ec8d39d49aff4cc234ce20c0dc218e3ab441c0061ffe1c641c29cf3a
|
|
BLAKE2b-256 checksum How to use checksums |
3ea9b76b7d8c9ccd13304af2672e70b7dd3d82cd081361011c0bdfe4a98e62c3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Release files / msp_py-0.1.0a1-py3-none-any.whl
| Download URL | msp_py-0.1.0a1-py3-none-any.whl |
|---|---|
| Size | 157.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
31ba932d9e1d4f387b2bbc610bbb01013e1ebf36a329a07956fda57331b8e411
|
|
BLAKE2b-256 checksum How to use checksums |
f3cb4f1669af7212fb5b62d1342f9a78ce2a997ac4f7661eb75880074aaef488
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Security for msp-py 0.1.0a1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.