purra-mcp 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- purra_mcp-1.0.0/LICENSE +21 -0
- purra_mcp-1.0.0/PKG-INFO +149 -0
- purra_mcp-1.0.0/README.md +137 -0
- purra_mcp-1.0.0/pyproject.toml +17 -0
- purra_mcp-1.0.0/setup.cfg +4 -0
- purra_mcp-1.0.0/src/purra_mcp/__init__.py +329 -0
- purra_mcp-1.0.0/src/purra_mcp.egg-info/PKG-INFO +149 -0
- purra_mcp-1.0.0/src/purra_mcp.egg-info/SOURCES.txt +10 -0
- purra_mcp-1.0.0/src/purra_mcp.egg-info/dependency_links.txt +1 -0
- purra_mcp-1.0.0/src/purra_mcp.egg-info/requires.txt +2 -0
- purra_mcp-1.0.0/src/purra_mcp.egg-info/top_level.txt +1 -0
- purra_mcp-1.0.0/tests/test_protocol.py +349 -0
purra_mcp-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lybrands
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
purra_mcp-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: purra-mcp
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Host-owned, read-only MCP tools for PurrA
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: purra==1.0.0
|
|
10
|
+
Requires-Dist: mcp==1.29.1
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# purra-mcp (Python)
|
|
14
|
+
|
|
15
|
+
Development package for explicitly authorized, read-only MCP tools. Requires a
|
|
16
|
+
matching PurrA Core and the pinned official `mcp==1.29.1` SDK (v1 line). Core has
|
|
17
|
+
no MCP dependency. Install from this checkout with:
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
python -m pip install . ./integrations/mcp/python
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The application opens and initializes `ClientSession`, supplies credentials and
|
|
24
|
+
transport limits, and closes the connection. The adapter performs paginated
|
|
25
|
+
`tools/list` discovery and single `tools/call` requests on that session.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from mcp import ClientSession
|
|
29
|
+
from purra.contracts import ToolPolicy
|
|
30
|
+
from purra_mcp import McpCatalogMonitor, McpToolBinding, discover_mcp_tools
|
|
31
|
+
|
|
32
|
+
monitor = McpCatalogMonitor()
|
|
33
|
+
# read_stream/write_stream come from the application's chosen SDK transport.
|
|
34
|
+
try:
|
|
35
|
+
async with ClientSession(read_stream, write_stream,
|
|
36
|
+
message_handler=monitor.on_message) as client:
|
|
37
|
+
initialized = await client.initialize()
|
|
38
|
+
monitor.accept_protocol_version(initialized.protocolVersion)
|
|
39
|
+
catalog = await discover_mcp_tools(client, "documents", {
|
|
40
|
+
"remote.search": McpToolBinding(
|
|
41
|
+
local_name="search_documents",
|
|
42
|
+
policy=ToolPolicy(mode="read", title="Search documents"),
|
|
43
|
+
scope_validator=authorize_document_scope,
|
|
44
|
+
concurrency_safe=False,
|
|
45
|
+
),
|
|
46
|
+
}, monitor=monitor)
|
|
47
|
+
# Pass catalog.registrations to Core's InMemoryToolCatalog while this
|
|
48
|
+
# session remains open. authorize_document_scope(state, args, signal)
|
|
49
|
+
# returns None to allow or a non-empty denial string.
|
|
50
|
+
finally:
|
|
51
|
+
monitor.close()
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
If the host already has a message handler, compose it with `monitor.on_message`.
|
|
55
|
+
Feed the negotiated protocol from the actual initialization response, never a
|
|
56
|
+
configured guess. Mark the monitor closed in the host's disconnect/finally path.
|
|
57
|
+
Supported negotiated versions are `2025-06-18` and `2025-11-25`.
|
|
58
|
+
|
|
59
|
+
Every binding is an explicit host declaration: the remote tool really is
|
|
60
|
+
read-only, its local name and policy are authorized, and its scope validator is
|
|
61
|
+
appropriate. Pass `scope_validator=None` only when the host intentionally needs
|
|
62
|
+
no additional scope check. Remote annotations grant no authority. An incorrect
|
|
63
|
+
host read declaration cannot make a remote write safe. `concurrency_safe` records
|
|
64
|
+
the host's declaration; it does not enable parallel scheduling by itself.
|
|
65
|
+
|
|
66
|
+
Discovery returns a detached immutable snapshot with `schemaVersion=1`,
|
|
67
|
+
`serverId`, negotiated `protocolVersion`, `revisionDigest`, and entries sorted by
|
|
68
|
+
local name. The digest uses Core's `purra.json-identity/v1` over those fields
|
|
69
|
+
excluding the digest. Entry identity includes schemas, description, names,
|
|
70
|
+
read policy, and concurrency declaration. `notifications/tools/list_changed`
|
|
71
|
+
makes old registrations stale. Explicitly discover again and replace the host's
|
|
72
|
+
catalog at a safe boundary; an existing catalog never silently acquires tools.
|
|
73
|
+
|
|
74
|
+
Selected input and output schemas must satisfy Core's
|
|
75
|
+
`purra.output-schema/v1` object profile. Unsupported schemas fail discovery;
|
|
76
|
+
there is no schema weakening or parameter coercion. Unbound tools are not
|
|
77
|
+
registered. Successful results are JSON envelopes:
|
|
78
|
+
|
|
79
|
+
```json
|
|
80
|
+
{"text":["human-readable text"],"structured":{"count":3}}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`structured` is null when absent. An advertised output schema requires valid
|
|
84
|
+
`structuredContent`; JSON-looking text is never a substitute. Images, audio,
|
|
85
|
+
resource content/links, required remote tasks, and `isError` results fail closed.
|
|
86
|
+
The adapter does not register sampling, elicitation, resources, or task handlers.
|
|
87
|
+
The host must not enable those capabilities on this tools-only path.
|
|
88
|
+
|
|
89
|
+
`McpToolLimits` defaults: 32 pages, 256 tools, 1 MiB catalog, 64 KiB selected
|
|
90
|
+
schema, 8 KiB description, 64 KiB result/argument object budget, 128 content
|
|
91
|
+
blocks, and 30 seconds per RPC. Limits may be lowered; timeout may be raised to
|
|
92
|
+
300 seconds. Core adds depth/node/validation budgets. These are decoded-value
|
|
93
|
+
limits; enforce wire/frame/body limits in the host transport as well.
|
|
94
|
+
|
|
95
|
+
Discovery raises sanitized `McpAdapterError` codes. Tool failures return an empty
|
|
96
|
+
envelope plus `error_code`: `mcp_invalid_arguments`, `mcp_scope_denied`,
|
|
97
|
+
`mcp_catalog_stale`, `mcp_connection_closed`, `mcp_timeout`,
|
|
98
|
+
`mcp_protocol_error`, `mcp_transport_error`, `mcp_tool_error`,
|
|
99
|
+
`mcp_result_invalid`, `mcp_result_unsupported`, or `mcp_result_too_large`.
|
|
100
|
+
Core admission may reject the whole batch before the handler, using Core's
|
|
101
|
+
argument/scope error codes. Remote error messages are not returned to the model.
|
|
102
|
+
There are no adapter retries, implicit rediscovery, or hidden model calls.
|
|
103
|
+
|
|
104
|
+
The host must also handle failures around the transport context manager. In the
|
|
105
|
+
pinned Python Streamable HTTP SDK, a connection failure in a background HTTP
|
|
106
|
+
task can exit the entire session with an `ExceptionGroup`, interrupting the
|
|
107
|
+
awaiting tool call. This is a host session failure, not a returned adapter tool
|
|
108
|
+
error. Close the monitor in `finally`, discard the failed session and create a
|
|
109
|
+
new initialized session and catalog before resuming work. Do not expose raw
|
|
110
|
+
transport exceptions to the model. A lost response stream may instead remain
|
|
111
|
+
pending until the configured request timeout; disconnect detection is not
|
|
112
|
+
guaranteed to be immediate.
|
|
113
|
+
|
|
114
|
+
Cancellation stops local waiting and discards late results. The pinned Python
|
|
115
|
+
SDK removes the pending local request but does not send a cancellation
|
|
116
|
+
notification from `send_request`; remote execution can continue. The host owns
|
|
117
|
+
remote cancellation policy and connection shutdown. Neither cancellation nor a
|
|
118
|
+
read result's `effect_state="not_started"` proves remote execution did not occur:
|
|
119
|
+
that field describes the declared absence of host writes. No write tools are
|
|
120
|
+
supported by this adapter.
|
|
121
|
+
|
|
122
|
+
Tests use an official local SDK server and shared fixtures. The installed smoke
|
|
123
|
+
runs a separate stdio server owned and stopped by its host script. These checks
|
|
124
|
+
do not establish third-party MCP availability, Provider quality, or downstream
|
|
125
|
+
integration. See the [MCP tools specification](https://modelcontextprotocol.io/specification/2025-11-25/server/tools)
|
|
126
|
+
and [cancellation specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation).
|
|
127
|
+
|
|
128
|
+
Core's separately configured argument and result limits also apply. A result
|
|
129
|
+
accepted by the adapter may still exceed a lower Core result limit and fail
|
|
130
|
+
with `tool_result_too_large`. Align both budgets in the host configuration.
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
Unsupported schema metadata is rejected as well as unsupported validation
|
|
134
|
+
keywords. For example, `default` and `x-fastmcp-wrap-result` are outside
|
|
135
|
+
`purra.output-schema/v1`: a selected tool using either fails discovery with
|
|
136
|
+
`mcp_schema_unsupported` before `tools/call`. The adapter never strips these
|
|
137
|
+
fields to make a remote tool appear supported. Select compatible tools explicitly;
|
|
138
|
+
unselected unsupported tools do not widen the catalog. A working MCP handshake
|
|
139
|
+
alone does not establish tool compatibility.
|
|
140
|
+
|
|
141
|
+
MCP input/output schemas may declare the root `$schema` as exactly
|
|
142
|
+
`https://json-schema.org/draft/2020-12/schema`. The adapter recognizes this
|
|
143
|
+
MCP dialect declaration, retains it in the immutable snapshot and revision
|
|
144
|
+
digest, and compiles the remaining constraints with `purra.output-schema/v1`.
|
|
145
|
+
The full remote schema, including the declaration, counts against the schema
|
|
146
|
+
byte limit. Other dialect URIs, nested declarations, references, and unknown
|
|
147
|
+
keywords remain unsupported; no schema document is fetched. This does not add
|
|
148
|
+
`$schema` to the Core structured-output profile or promise full JSON Schema
|
|
149
|
+
2020-12 support. See the [MCP schema rules](https://modelcontextprotocol.io/specification/2025-11-25/server/tools).
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# purra-mcp (Python)
|
|
2
|
+
|
|
3
|
+
Development package for explicitly authorized, read-only MCP tools. Requires a
|
|
4
|
+
matching PurrA Core and the pinned official `mcp==1.29.1` SDK (v1 line). Core has
|
|
5
|
+
no MCP dependency. Install from this checkout with:
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
python -m pip install . ./integrations/mcp/python
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The application opens and initializes `ClientSession`, supplies credentials and
|
|
12
|
+
transport limits, and closes the connection. The adapter performs paginated
|
|
13
|
+
`tools/list` discovery and single `tools/call` requests on that session.
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from mcp import ClientSession
|
|
17
|
+
from purra.contracts import ToolPolicy
|
|
18
|
+
from purra_mcp import McpCatalogMonitor, McpToolBinding, discover_mcp_tools
|
|
19
|
+
|
|
20
|
+
monitor = McpCatalogMonitor()
|
|
21
|
+
# read_stream/write_stream come from the application's chosen SDK transport.
|
|
22
|
+
try:
|
|
23
|
+
async with ClientSession(read_stream, write_stream,
|
|
24
|
+
message_handler=monitor.on_message) as client:
|
|
25
|
+
initialized = await client.initialize()
|
|
26
|
+
monitor.accept_protocol_version(initialized.protocolVersion)
|
|
27
|
+
catalog = await discover_mcp_tools(client, "documents", {
|
|
28
|
+
"remote.search": McpToolBinding(
|
|
29
|
+
local_name="search_documents",
|
|
30
|
+
policy=ToolPolicy(mode="read", title="Search documents"),
|
|
31
|
+
scope_validator=authorize_document_scope,
|
|
32
|
+
concurrency_safe=False,
|
|
33
|
+
),
|
|
34
|
+
}, monitor=monitor)
|
|
35
|
+
# Pass catalog.registrations to Core's InMemoryToolCatalog while this
|
|
36
|
+
# session remains open. authorize_document_scope(state, args, signal)
|
|
37
|
+
# returns None to allow or a non-empty denial string.
|
|
38
|
+
finally:
|
|
39
|
+
monitor.close()
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
If the host already has a message handler, compose it with `monitor.on_message`.
|
|
43
|
+
Feed the negotiated protocol from the actual initialization response, never a
|
|
44
|
+
configured guess. Mark the monitor closed in the host's disconnect/finally path.
|
|
45
|
+
Supported negotiated versions are `2025-06-18` and `2025-11-25`.
|
|
46
|
+
|
|
47
|
+
Every binding is an explicit host declaration: the remote tool really is
|
|
48
|
+
read-only, its local name and policy are authorized, and its scope validator is
|
|
49
|
+
appropriate. Pass `scope_validator=None` only when the host intentionally needs
|
|
50
|
+
no additional scope check. Remote annotations grant no authority. An incorrect
|
|
51
|
+
host read declaration cannot make a remote write safe. `concurrency_safe` records
|
|
52
|
+
the host's declaration; it does not enable parallel scheduling by itself.
|
|
53
|
+
|
|
54
|
+
Discovery returns a detached immutable snapshot with `schemaVersion=1`,
|
|
55
|
+
`serverId`, negotiated `protocolVersion`, `revisionDigest`, and entries sorted by
|
|
56
|
+
local name. The digest uses Core's `purra.json-identity/v1` over those fields
|
|
57
|
+
excluding the digest. Entry identity includes schemas, description, names,
|
|
58
|
+
read policy, and concurrency declaration. `notifications/tools/list_changed`
|
|
59
|
+
makes old registrations stale. Explicitly discover again and replace the host's
|
|
60
|
+
catalog at a safe boundary; an existing catalog never silently acquires tools.
|
|
61
|
+
|
|
62
|
+
Selected input and output schemas must satisfy Core's
|
|
63
|
+
`purra.output-schema/v1` object profile. Unsupported schemas fail discovery;
|
|
64
|
+
there is no schema weakening or parameter coercion. Unbound tools are not
|
|
65
|
+
registered. Successful results are JSON envelopes:
|
|
66
|
+
|
|
67
|
+
```json
|
|
68
|
+
{"text":["human-readable text"],"structured":{"count":3}}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`structured` is null when absent. An advertised output schema requires valid
|
|
72
|
+
`structuredContent`; JSON-looking text is never a substitute. Images, audio,
|
|
73
|
+
resource content/links, required remote tasks, and `isError` results fail closed.
|
|
74
|
+
The adapter does not register sampling, elicitation, resources, or task handlers.
|
|
75
|
+
The host must not enable those capabilities on this tools-only path.
|
|
76
|
+
|
|
77
|
+
`McpToolLimits` defaults: 32 pages, 256 tools, 1 MiB catalog, 64 KiB selected
|
|
78
|
+
schema, 8 KiB description, 64 KiB result/argument object budget, 128 content
|
|
79
|
+
blocks, and 30 seconds per RPC. Limits may be lowered; timeout may be raised to
|
|
80
|
+
300 seconds. Core adds depth/node/validation budgets. These are decoded-value
|
|
81
|
+
limits; enforce wire/frame/body limits in the host transport as well.
|
|
82
|
+
|
|
83
|
+
Discovery raises sanitized `McpAdapterError` codes. Tool failures return an empty
|
|
84
|
+
envelope plus `error_code`: `mcp_invalid_arguments`, `mcp_scope_denied`,
|
|
85
|
+
`mcp_catalog_stale`, `mcp_connection_closed`, `mcp_timeout`,
|
|
86
|
+
`mcp_protocol_error`, `mcp_transport_error`, `mcp_tool_error`,
|
|
87
|
+
`mcp_result_invalid`, `mcp_result_unsupported`, or `mcp_result_too_large`.
|
|
88
|
+
Core admission may reject the whole batch before the handler, using Core's
|
|
89
|
+
argument/scope error codes. Remote error messages are not returned to the model.
|
|
90
|
+
There are no adapter retries, implicit rediscovery, or hidden model calls.
|
|
91
|
+
|
|
92
|
+
The host must also handle failures around the transport context manager. In the
|
|
93
|
+
pinned Python Streamable HTTP SDK, a connection failure in a background HTTP
|
|
94
|
+
task can exit the entire session with an `ExceptionGroup`, interrupting the
|
|
95
|
+
awaiting tool call. This is a host session failure, not a returned adapter tool
|
|
96
|
+
error. Close the monitor in `finally`, discard the failed session and create a
|
|
97
|
+
new initialized session and catalog before resuming work. Do not expose raw
|
|
98
|
+
transport exceptions to the model. A lost response stream may instead remain
|
|
99
|
+
pending until the configured request timeout; disconnect detection is not
|
|
100
|
+
guaranteed to be immediate.
|
|
101
|
+
|
|
102
|
+
Cancellation stops local waiting and discards late results. The pinned Python
|
|
103
|
+
SDK removes the pending local request but does not send a cancellation
|
|
104
|
+
notification from `send_request`; remote execution can continue. The host owns
|
|
105
|
+
remote cancellation policy and connection shutdown. Neither cancellation nor a
|
|
106
|
+
read result's `effect_state="not_started"` proves remote execution did not occur:
|
|
107
|
+
that field describes the declared absence of host writes. No write tools are
|
|
108
|
+
supported by this adapter.
|
|
109
|
+
|
|
110
|
+
Tests use an official local SDK server and shared fixtures. The installed smoke
|
|
111
|
+
runs a separate stdio server owned and stopped by its host script. These checks
|
|
112
|
+
do not establish third-party MCP availability, Provider quality, or downstream
|
|
113
|
+
integration. See the [MCP tools specification](https://modelcontextprotocol.io/specification/2025-11-25/server/tools)
|
|
114
|
+
and [cancellation specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation).
|
|
115
|
+
|
|
116
|
+
Core's separately configured argument and result limits also apply. A result
|
|
117
|
+
accepted by the adapter may still exceed a lower Core result limit and fail
|
|
118
|
+
with `tool_result_too_large`. Align both budgets in the host configuration.
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
Unsupported schema metadata is rejected as well as unsupported validation
|
|
122
|
+
keywords. For example, `default` and `x-fastmcp-wrap-result` are outside
|
|
123
|
+
`purra.output-schema/v1`: a selected tool using either fails discovery with
|
|
124
|
+
`mcp_schema_unsupported` before `tools/call`. The adapter never strips these
|
|
125
|
+
fields to make a remote tool appear supported. Select compatible tools explicitly;
|
|
126
|
+
unselected unsupported tools do not widen the catalog. A working MCP handshake
|
|
127
|
+
alone does not establish tool compatibility.
|
|
128
|
+
|
|
129
|
+
MCP input/output schemas may declare the root `$schema` as exactly
|
|
130
|
+
`https://json-schema.org/draft/2020-12/schema`. The adapter recognizes this
|
|
131
|
+
MCP dialect declaration, retains it in the immutable snapshot and revision
|
|
132
|
+
digest, and compiles the remaining constraints with `purra.output-schema/v1`.
|
|
133
|
+
The full remote schema, including the declaration, counts against the schema
|
|
134
|
+
byte limit. Other dialect URIs, nested declarations, references, and unknown
|
|
135
|
+
keywords remain unsupported; no schema document is fetched. This does not add
|
|
136
|
+
`$schema` to the Core structured-output profile or promise full JSON Schema
|
|
137
|
+
2020-12 support. See the [MCP schema rules](https://modelcontextprotocol.io/specification/2025-11-25/server/tools).
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
[project]
|
|
5
|
+
name = "purra-mcp"
|
|
6
|
+
version = "1.0.0"
|
|
7
|
+
description = "Host-owned, read-only MCP tools for PurrA"
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
dependencies = ["purra==1.0.0", "mcp==1.29.1"]
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
[tool.setuptools.packages.find]
|
|
13
|
+
where = ["src"]
|
|
14
|
+
[tool.pytest.ini_options]
|
|
15
|
+
pythonpath = ["src", "../../../src"]
|
|
16
|
+
testpaths = ["tests"]
|
|
17
|
+
addopts = "-ra -q"
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Read-only tools through a host-owned, initialized official MCP session."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass, field, replace
|
|
9
|
+
from datetime import timedelta
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from mcp import ClientSession, types
|
|
13
|
+
from mcp.shared.exceptions import McpError
|
|
14
|
+
from purra.cancellation import OperationCanceled, await_with_cancellation, raise_if_stopped
|
|
15
|
+
from purra.contracts import ToolHandlerResult, ToolPolicy, ToolSchema
|
|
16
|
+
from purra.errors import CodedAgentCoreError
|
|
17
|
+
from purra.json_values import freeze_json_mapping, thaw_json_mapping
|
|
18
|
+
from purra.ports import ScopeValidator, ToolRegistration
|
|
19
|
+
from purra.structured import StructuredOutputContract, StructuredOutputError, StructuredOutputLimits, json_identity_digest
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class McpAdapterError(CodedAgentCoreError):
|
|
23
|
+
"""A sanitized boundary failure; remote error messages are never attached."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _fail(code):
|
|
27
|
+
raise McpAdapterError("MCP tool boundary rejected the operation", code=code)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class McpToolLimits:
|
|
32
|
+
max_pages: int = 32
|
|
33
|
+
max_tools: int = 256
|
|
34
|
+
max_catalog_bytes: int = 1_048_576
|
|
35
|
+
max_schema_bytes: int = 65_536
|
|
36
|
+
max_description_bytes: int = 8_192
|
|
37
|
+
max_result_bytes: int = 65_536
|
|
38
|
+
max_content_blocks: int = 128
|
|
39
|
+
timeout_ms: int = 30_000
|
|
40
|
+
|
|
41
|
+
def __post_init__(self):
|
|
42
|
+
maxima = (32, 256, 1_048_576, 65_536, 8_192, 65_536, 128, 300_000)
|
|
43
|
+
for name, maximum in zip(self.__dataclass_fields__, maxima):
|
|
44
|
+
if type(getattr(self, name)) is not int or not 1 <= getattr(self, name) <= maximum:
|
|
45
|
+
raise ValueError(f"{name} must be a positive integer at most {maximum}")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class McpCatalogMonitor:
|
|
49
|
+
"""Host-fed protocol/notification state; never owns or closes the session."""
|
|
50
|
+
def __init__(self):
|
|
51
|
+
self._revision = 0
|
|
52
|
+
self._closed = False
|
|
53
|
+
self._protocol = None
|
|
54
|
+
|
|
55
|
+
def accept_protocol_version(self, version: str) -> None:
|
|
56
|
+
if version not in {"2025-06-18", "2025-11-25"}:
|
|
57
|
+
self.close()
|
|
58
|
+
_fail("mcp_protocol_unsupported")
|
|
59
|
+
if self._protocol is not None and self._protocol != version:
|
|
60
|
+
self.close()
|
|
61
|
+
_fail("mcp_protocol_conflict")
|
|
62
|
+
self._protocol = version
|
|
63
|
+
|
|
64
|
+
async def on_message(self, message) -> None:
|
|
65
|
+
if isinstance(message, Exception):
|
|
66
|
+
self.close()
|
|
67
|
+
elif isinstance(message, types.ServerNotification) and isinstance(message.root, types.ToolListChangedNotification):
|
|
68
|
+
self._revision += 1
|
|
69
|
+
|
|
70
|
+
def close(self) -> None:
|
|
71
|
+
self._closed = True
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def revision(self):
|
|
75
|
+
return self._revision
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def protocol_version(self):
|
|
79
|
+
return self._protocol
|
|
80
|
+
|
|
81
|
+
def check(self, revision: int) -> None:
|
|
82
|
+
if self._closed:
|
|
83
|
+
_fail("mcp_connection_closed")
|
|
84
|
+
if self._protocol is None:
|
|
85
|
+
_fail("mcp_not_initialized")
|
|
86
|
+
if revision != self._revision:
|
|
87
|
+
_fail("mcp_catalog_stale")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True, slots=True)
|
|
91
|
+
class McpToolBinding:
|
|
92
|
+
local_name: str
|
|
93
|
+
policy: ToolPolicy
|
|
94
|
+
scope_validator: ScopeValidator | None
|
|
95
|
+
concurrency_safe: bool = False
|
|
96
|
+
|
|
97
|
+
def __post_init__(self):
|
|
98
|
+
if not isinstance(self.local_name, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,63}", self.local_name):
|
|
99
|
+
_fail("mcp_binding_invalid")
|
|
100
|
+
if not isinstance(self.policy, ToolPolicy) or self.policy.mode != "read" or self.policy.risk_level != "read":
|
|
101
|
+
_fail("mcp_binding_invalid")
|
|
102
|
+
if self.scope_validator is not None and not callable(self.scope_validator):
|
|
103
|
+
_fail("mcp_binding_invalid")
|
|
104
|
+
if type(self.concurrency_safe) is not bool:
|
|
105
|
+
_fail("mcp_binding_invalid")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True, slots=True)
|
|
109
|
+
class McpToolSnapshot:
|
|
110
|
+
server_id: str
|
|
111
|
+
protocol_version: str
|
|
112
|
+
revision_digest: str
|
|
113
|
+
entries: tuple[Mapping[str, Any], ...]
|
|
114
|
+
schema_version: int = 1
|
|
115
|
+
|
|
116
|
+
def __post_init__(self):
|
|
117
|
+
object.__setattr__(self, "entries", tuple(freeze_json_mapping(e) for e in self.entries))
|
|
118
|
+
|
|
119
|
+
def to_mapping(self):
|
|
120
|
+
return {"schemaVersion": self.schema_version, "serverId": self.server_id,
|
|
121
|
+
"protocolVersion": self.protocol_version, "revisionDigest": self.revision_digest,
|
|
122
|
+
"entries": [thaw_json_mapping(e) for e in self.entries]}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass(frozen=True, slots=True)
|
|
126
|
+
class McpToolCatalog:
|
|
127
|
+
snapshot: McpToolSnapshot
|
|
128
|
+
registrations: tuple[ToolRegistration, ...]
|
|
129
|
+
_monitor: McpCatalogMonitor = field(repr=False)
|
|
130
|
+
_revision: int = field(repr=False)
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def stale(self):
|
|
134
|
+
try:
|
|
135
|
+
self._monitor.check(self._revision)
|
|
136
|
+
return False
|
|
137
|
+
except McpAdapterError:
|
|
138
|
+
return True
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _bytes(value):
|
|
142
|
+
return len(json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8"))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _contract(schema, limits):
|
|
146
|
+
try:
|
|
147
|
+
return StructuredOutputContract("mcp.object", "1", schema,
|
|
148
|
+
limits=replace(StructuredOutputLimits(), schema_bytes=limits.max_schema_bytes,
|
|
149
|
+
output_bytes=limits.max_result_bytes))
|
|
150
|
+
except (StructuredOutputError, TypeError, ValueError):
|
|
151
|
+
_fail("mcp_schema_unsupported")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _remote_contract(schema, limits):
|
|
155
|
+
# MCP's root dialect declaration selects the validated subset; it is not a constraint.
|
|
156
|
+
try:
|
|
157
|
+
if _bytes(schema) > limits.max_schema_bytes:
|
|
158
|
+
_fail("mcp_schema_unsupported")
|
|
159
|
+
declared = "$schema" in schema
|
|
160
|
+
if declared and schema["$schema"] != "https://json-schema.org/draft/2020-12/schema":
|
|
161
|
+
_fail("mcp_schema_unsupported")
|
|
162
|
+
contract = _contract({key: value for key, value in schema.items() if key != "$schema"}, limits)
|
|
163
|
+
snapshot = thaw_json_mapping(contract.schema)
|
|
164
|
+
if declared:
|
|
165
|
+
snapshot["$schema"] = schema["$schema"]
|
|
166
|
+
return contract, snapshot
|
|
167
|
+
except (TypeError, ValueError, OverflowError, RecursionError):
|
|
168
|
+
_fail("mcp_schema_unsupported")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
async def _request(client, request, result_type, limits, signal):
|
|
172
|
+
raise_if_stopped(signal)
|
|
173
|
+
try:
|
|
174
|
+
# Raw official SDK request avoids call_tool's implicit catalog refresh.
|
|
175
|
+
async with asyncio.timeout(limits.timeout_ms / 1000):
|
|
176
|
+
return await await_with_cancellation(client.send_request(request, result_type,
|
|
177
|
+
request_read_timeout_seconds=timedelta(milliseconds=limits.timeout_ms)), signal)
|
|
178
|
+
except OperationCanceled:
|
|
179
|
+
raise
|
|
180
|
+
except TimeoutError:
|
|
181
|
+
_fail("mcp_timeout")
|
|
182
|
+
except McpError as error:
|
|
183
|
+
code = ("mcp_timeout" if error.error.code in {408, -32001} else
|
|
184
|
+
"mcp_transport_error" if error.error.code == types.CONNECTION_CLOSED else "mcp_protocol_error")
|
|
185
|
+
except (ValueError, TypeError):
|
|
186
|
+
code = "mcp_result_invalid"
|
|
187
|
+
except Exception:
|
|
188
|
+
code = "mcp_transport_error"
|
|
189
|
+
_fail(code)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _result(raw, output, limits):
|
|
193
|
+
if raw.isError:
|
|
194
|
+
_fail("mcp_tool_error")
|
|
195
|
+
if len(raw.content) > limits.max_content_blocks:
|
|
196
|
+
_fail("mcp_result_too_large")
|
|
197
|
+
text = []
|
|
198
|
+
for block in raw.content:
|
|
199
|
+
if not isinstance(block, types.TextContent):
|
|
200
|
+
_fail("mcp_result_unsupported")
|
|
201
|
+
text.append(block.text)
|
|
202
|
+
envelope = {"text": text, "structured": raw.structuredContent}
|
|
203
|
+
try:
|
|
204
|
+
if _bytes(raw.model_dump(mode="json", by_alias=True, exclude_none=True)) > limits.max_result_bytes:
|
|
205
|
+
_fail("mcp_result_too_large")
|
|
206
|
+
value = _contract({"type": "object"}, limits).validate_value(envelope)
|
|
207
|
+
if output is not None:
|
|
208
|
+
output.validate_value(raw.structuredContent)
|
|
209
|
+
except StructuredOutputError:
|
|
210
|
+
_fail("mcp_result_invalid")
|
|
211
|
+
except (ValueError, TypeError, OverflowError, RecursionError):
|
|
212
|
+
_fail("mcp_result_invalid")
|
|
213
|
+
return value
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _registration(client, remote, entry, binding, contract, output, monitor, revision, limits):
|
|
217
|
+
async def scope(state, arguments, signal=None):
|
|
218
|
+
monitor.check(revision)
|
|
219
|
+
raise_if_stopped(signal)
|
|
220
|
+
if binding.scope_validator is not None:
|
|
221
|
+
return await binding.scope_validator(state, arguments, signal)
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
async def run(state, arguments, signal=None):
|
|
225
|
+
try:
|
|
226
|
+
monitor.check(revision)
|
|
227
|
+
try:
|
|
228
|
+
value = contract.validate_value(arguments)
|
|
229
|
+
except StructuredOutputError:
|
|
230
|
+
_fail("mcp_invalid_arguments")
|
|
231
|
+
decision = await scope(state, value, signal)
|
|
232
|
+
if decision is not None and str(decision).strip():
|
|
233
|
+
_fail("mcp_scope_denied")
|
|
234
|
+
monitor.check(revision)
|
|
235
|
+
raise_if_stopped(signal)
|
|
236
|
+
result = await _request(client, types.ClientRequest(types.CallToolRequest(
|
|
237
|
+
params=types.CallToolRequestParams(name=remote, arguments=thaw_json_mapping(value)))),
|
|
238
|
+
types.CallToolResult, limits, signal)
|
|
239
|
+
monitor.check(revision)
|
|
240
|
+
envelope = _result(result, output, limits)
|
|
241
|
+
return ToolHandlerResult(json.dumps(thaw_json_mapping(envelope), ensure_ascii=False, separators=(",", ":")), effect_state="not_started")
|
|
242
|
+
except McpAdapterError as error:
|
|
243
|
+
return ToolHandlerResult('{"text":[],"structured":null}', error_code=error.code, effect_state="not_started")
|
|
244
|
+
|
|
245
|
+
return ToolRegistration(ToolSchema(binding.local_name, entry["description"] or binding.policy.title, contract.schema),
|
|
246
|
+
run, binding.policy, scope_validator=scope, argument_contract=contract, concurrency_safe=binding.concurrency_safe,
|
|
247
|
+
max_argument_chars=limits.max_result_bytes)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
async def discover_mcp_tools(client: ClientSession, server_id: str,
|
|
251
|
+
bindings: Mapping[str, McpToolBinding], *, monitor: McpCatalogMonitor,
|
|
252
|
+
limits: McpToolLimits = McpToolLimits(), signal=None) -> McpToolCatalog:
|
|
253
|
+
if not isinstance(client, ClientSession) or not isinstance(monitor, McpCatalogMonitor) or not isinstance(limits, McpToolLimits):
|
|
254
|
+
_fail("mcp_binding_invalid")
|
|
255
|
+
if not isinstance(server_id, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", server_id):
|
|
256
|
+
_fail("mcp_binding_invalid")
|
|
257
|
+
if not isinstance(bindings, Mapping) or not bindings or len(bindings) > limits.max_tools:
|
|
258
|
+
_fail("mcp_binding_invalid")
|
|
259
|
+
bound = dict(bindings)
|
|
260
|
+
if any(not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", name)
|
|
261
|
+
or not isinstance(binding, McpToolBinding) for name, binding in bound.items()):
|
|
262
|
+
_fail("mcp_binding_invalid")
|
|
263
|
+
if len({binding.local_name for binding in bound.values()}) != len(bound):
|
|
264
|
+
_fail("mcp_name_conflict")
|
|
265
|
+
revision = monitor.revision
|
|
266
|
+
monitor.check(revision)
|
|
267
|
+
capabilities = client.get_server_capabilities()
|
|
268
|
+
if capabilities is None or capabilities.tools is None:
|
|
269
|
+
_fail("mcp_tools_unavailable")
|
|
270
|
+
seen, cursors, found = set(), set(), {}
|
|
271
|
+
cursor = None
|
|
272
|
+
total_bytes = 0
|
|
273
|
+
for _ in range(limits.max_pages):
|
|
274
|
+
monitor.check(revision)
|
|
275
|
+
result = await _request(client, types.ClientRequest(types.ListToolsRequest(
|
|
276
|
+
params=types.PaginatedRequestParams(cursor=cursor) if cursor is not None else None)),
|
|
277
|
+
types.ListToolsResult, limits, signal)
|
|
278
|
+
monitor.check(revision)
|
|
279
|
+
try:
|
|
280
|
+
total_bytes += _bytes(result.model_dump(mode="json", by_alias=True, exclude_none=True))
|
|
281
|
+
except (ValueError, TypeError, OverflowError, RecursionError):
|
|
282
|
+
_fail("mcp_catalog_invalid")
|
|
283
|
+
if total_bytes > limits.max_catalog_bytes or len(seen) + len(result.tools) > limits.max_tools:
|
|
284
|
+
_fail("mcp_catalog_limit_exceeded")
|
|
285
|
+
for tool in result.tools:
|
|
286
|
+
if tool.name in seen:
|
|
287
|
+
_fail("mcp_name_conflict")
|
|
288
|
+
seen.add(tool.name)
|
|
289
|
+
if tool.name not in bound:
|
|
290
|
+
continue
|
|
291
|
+
binding = bound[tool.name]
|
|
292
|
+
description = tool.description or ""
|
|
293
|
+
if len(description.encode("utf-8")) > limits.max_description_bytes:
|
|
294
|
+
_fail("mcp_catalog_limit_exceeded")
|
|
295
|
+
if tool.execution is not None and tool.execution.taskSupport == "required":
|
|
296
|
+
_fail("mcp_tool_unsupported")
|
|
297
|
+
contract, input_schema = _remote_contract(tool.inputSchema, limits)
|
|
298
|
+
output, output_schema = _remote_contract(tool.outputSchema, limits) if tool.outputSchema is not None else (None, None)
|
|
299
|
+
entry = {"remoteName": tool.name, "localName": binding.local_name,
|
|
300
|
+
"description": description, "inputSchema": input_schema,
|
|
301
|
+
"outputSchema": output_schema,
|
|
302
|
+
"policy": {"mode": "read", "title": binding.policy.title, "riskLevel": "read"},
|
|
303
|
+
"concurrencySafe": binding.concurrency_safe}
|
|
304
|
+
found[tool.name] = (entry, binding, contract, output)
|
|
305
|
+
cursor = result.nextCursor
|
|
306
|
+
if cursor is None:
|
|
307
|
+
break
|
|
308
|
+
if not cursor or len(cursor.encode("utf-8")) > 512 or cursor in cursors:
|
|
309
|
+
_fail("mcp_pagination_invalid")
|
|
310
|
+
cursors.add(cursor)
|
|
311
|
+
else:
|
|
312
|
+
_fail("mcp_catalog_limit_exceeded")
|
|
313
|
+
if found.keys() != bound.keys():
|
|
314
|
+
_fail("mcp_binding_missing")
|
|
315
|
+
ordered = sorted(found.items(), key=lambda item: item[1][0]["localName"])
|
|
316
|
+
entries = tuple(item[1][0] for item in ordered)
|
|
317
|
+
identity = {"schemaVersion": 1, "serverId": server_id, "protocolVersion": monitor.protocol_version, "entries": entries}
|
|
318
|
+
try:
|
|
319
|
+
digest = json_identity_digest(identity)
|
|
320
|
+
except (ValueError, TypeError):
|
|
321
|
+
_fail("mcp_catalog_limit_exceeded")
|
|
322
|
+
snapshot = McpToolSnapshot(server_id, monitor.protocol_version, digest, entries)
|
|
323
|
+
registrations = tuple(_registration(client, remote, entry, binding, contract, output, monitor, revision, limits)
|
|
324
|
+
for remote, (entry, binding, contract, output) in ordered)
|
|
325
|
+
monitor.check(revision)
|
|
326
|
+
return McpToolCatalog(snapshot, registrations, monitor, revision)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
__all__ = ["McpAdapterError", "McpToolLimits", "McpCatalogMonitor", "McpToolBinding", "McpToolSnapshot", "McpToolCatalog", "discover_mcp_tools"]
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: purra-mcp
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Host-owned, read-only MCP tools for PurrA
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: purra==1.0.0
|
|
10
|
+
Requires-Dist: mcp==1.29.1
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# purra-mcp (Python)
|
|
14
|
+
|
|
15
|
+
Development package for explicitly authorized, read-only MCP tools. Requires a
|
|
16
|
+
matching PurrA Core and the pinned official `mcp==1.29.1` SDK (v1 line). Core has
|
|
17
|
+
no MCP dependency. Install from this checkout with:
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
python -m pip install . ./integrations/mcp/python
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The application opens and initializes `ClientSession`, supplies credentials and
|
|
24
|
+
transport limits, and closes the connection. The adapter performs paginated
|
|
25
|
+
`tools/list` discovery and single `tools/call` requests on that session.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from mcp import ClientSession
|
|
29
|
+
from purra.contracts import ToolPolicy
|
|
30
|
+
from purra_mcp import McpCatalogMonitor, McpToolBinding, discover_mcp_tools
|
|
31
|
+
|
|
32
|
+
monitor = McpCatalogMonitor()
|
|
33
|
+
# read_stream/write_stream come from the application's chosen SDK transport.
|
|
34
|
+
try:
|
|
35
|
+
async with ClientSession(read_stream, write_stream,
|
|
36
|
+
message_handler=monitor.on_message) as client:
|
|
37
|
+
initialized = await client.initialize()
|
|
38
|
+
monitor.accept_protocol_version(initialized.protocolVersion)
|
|
39
|
+
catalog = await discover_mcp_tools(client, "documents", {
|
|
40
|
+
"remote.search": McpToolBinding(
|
|
41
|
+
local_name="search_documents",
|
|
42
|
+
policy=ToolPolicy(mode="read", title="Search documents"),
|
|
43
|
+
scope_validator=authorize_document_scope,
|
|
44
|
+
concurrency_safe=False,
|
|
45
|
+
),
|
|
46
|
+
}, monitor=monitor)
|
|
47
|
+
# Pass catalog.registrations to Core's InMemoryToolCatalog while this
|
|
48
|
+
# session remains open. authorize_document_scope(state, args, signal)
|
|
49
|
+
# returns None to allow or a non-empty denial string.
|
|
50
|
+
finally:
|
|
51
|
+
monitor.close()
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
If the host already has a message handler, compose it with `monitor.on_message`.
|
|
55
|
+
Feed the negotiated protocol from the actual initialization response, never a
|
|
56
|
+
configured guess. Mark the monitor closed in the host's disconnect/finally path.
|
|
57
|
+
Supported negotiated versions are `2025-06-18` and `2025-11-25`.
|
|
58
|
+
|
|
59
|
+
Every binding is an explicit host declaration: the remote tool really is
|
|
60
|
+
read-only, its local name and policy are authorized, and its scope validator is
|
|
61
|
+
appropriate. Pass `scope_validator=None` only when the host intentionally needs
|
|
62
|
+
no additional scope check. Remote annotations grant no authority. An incorrect
|
|
63
|
+
host read declaration cannot make a remote write safe. `concurrency_safe` records
|
|
64
|
+
the host's declaration; it does not enable parallel scheduling by itself.
|
|
65
|
+
|
|
66
|
+
Discovery returns a detached immutable snapshot with `schemaVersion=1`,
|
|
67
|
+
`serverId`, negotiated `protocolVersion`, `revisionDigest`, and entries sorted by
|
|
68
|
+
local name. The digest uses Core's `purra.json-identity/v1` over those fields
|
|
69
|
+
excluding the digest. Entry identity includes schemas, description, names,
|
|
70
|
+
read policy, and concurrency declaration. `notifications/tools/list_changed`
|
|
71
|
+
makes old registrations stale. Explicitly discover again and replace the host's
|
|
72
|
+
catalog at a safe boundary; an existing catalog never silently acquires tools.
|
|
73
|
+
|
|
74
|
+
Selected input and output schemas must satisfy Core's
|
|
75
|
+
`purra.output-schema/v1` object profile. Unsupported schemas fail discovery;
|
|
76
|
+
there is no schema weakening or parameter coercion. Unbound tools are not
|
|
77
|
+
registered. Successful results are JSON envelopes:
|
|
78
|
+
|
|
79
|
+
```json
|
|
80
|
+
{"text":["human-readable text"],"structured":{"count":3}}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`structured` is null when absent. An advertised output schema requires valid
|
|
84
|
+
`structuredContent`; JSON-looking text is never a substitute. Images, audio,
|
|
85
|
+
resource content/links, required remote tasks, and `isError` results fail closed.
|
|
86
|
+
The adapter does not register sampling, elicitation, resources, or task handlers.
|
|
87
|
+
The host must not enable those capabilities on this tools-only path.
|
|
88
|
+
|
|
89
|
+
`McpToolLimits` defaults: 32 pages, 256 tools, 1 MiB catalog, 64 KiB selected
|
|
90
|
+
schema, 8 KiB description, 64 KiB result/argument object budget, 128 content
|
|
91
|
+
blocks, and 30 seconds per RPC. Limits may be lowered; timeout may be raised to
|
|
92
|
+
300 seconds. Core adds depth/node/validation budgets. These are decoded-value
|
|
93
|
+
limits; enforce wire/frame/body limits in the host transport as well.
|
|
94
|
+
|
|
95
|
+
Discovery raises sanitized `McpAdapterError` codes. Tool failures return an empty
|
|
96
|
+
envelope plus `error_code`: `mcp_invalid_arguments`, `mcp_scope_denied`,
|
|
97
|
+
`mcp_catalog_stale`, `mcp_connection_closed`, `mcp_timeout`,
|
|
98
|
+
`mcp_protocol_error`, `mcp_transport_error`, `mcp_tool_error`,
|
|
99
|
+
`mcp_result_invalid`, `mcp_result_unsupported`, or `mcp_result_too_large`.
|
|
100
|
+
Core admission may reject the whole batch before the handler, using Core's
|
|
101
|
+
argument/scope error codes. Remote error messages are not returned to the model.
|
|
102
|
+
There are no adapter retries, implicit rediscovery, or hidden model calls.
|
|
103
|
+
|
|
104
|
+
The host must also handle failures around the transport context manager. In the
|
|
105
|
+
pinned Python Streamable HTTP SDK, a connection failure in a background HTTP
|
|
106
|
+
task can exit the entire session with an `ExceptionGroup`, interrupting the
|
|
107
|
+
awaiting tool call. This is a host session failure, not a returned adapter tool
|
|
108
|
+
error. Close the monitor in `finally`, discard the failed session and create a
|
|
109
|
+
new initialized session and catalog before resuming work. Do not expose raw
|
|
110
|
+
transport exceptions to the model. A lost response stream may instead remain
|
|
111
|
+
pending until the configured request timeout; disconnect detection is not
|
|
112
|
+
guaranteed to be immediate.
|
|
113
|
+
|
|
114
|
+
Cancellation stops local waiting and discards late results. The pinned Python
|
|
115
|
+
SDK removes the pending local request but does not send a cancellation
|
|
116
|
+
notification from `send_request`; remote execution can continue. The host owns
|
|
117
|
+
remote cancellation policy and connection shutdown. Neither cancellation nor a
|
|
118
|
+
read result's `effect_state="not_started"` proves remote execution did not occur:
|
|
119
|
+
that field describes the declared absence of host writes. No write tools are
|
|
120
|
+
supported by this adapter.
|
|
121
|
+
|
|
122
|
+
Tests use an official local SDK server and shared fixtures. The installed smoke
|
|
123
|
+
runs a separate stdio server owned and stopped by its host script. These checks
|
|
124
|
+
do not establish third-party MCP availability, Provider quality, or downstream
|
|
125
|
+
integration. See the [MCP tools specification](https://modelcontextprotocol.io/specification/2025-11-25/server/tools)
|
|
126
|
+
and [cancellation specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation).
|
|
127
|
+
|
|
128
|
+
Core's separately configured argument and result limits also apply. A result
|
|
129
|
+
accepted by the adapter may still exceed a lower Core result limit and fail
|
|
130
|
+
with `tool_result_too_large`. Align both budgets in the host configuration.
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
Unsupported schema metadata is rejected as well as unsupported validation
|
|
134
|
+
keywords. For example, `default` and `x-fastmcp-wrap-result` are outside
|
|
135
|
+
`purra.output-schema/v1`: a selected tool using either fails discovery with
|
|
136
|
+
`mcp_schema_unsupported` before `tools/call`. The adapter never strips these
|
|
137
|
+
fields to make a remote tool appear supported. Select compatible tools explicitly;
|
|
138
|
+
unselected unsupported tools do not widen the catalog. A working MCP handshake
|
|
139
|
+
alone does not establish tool compatibility.
|
|
140
|
+
|
|
141
|
+
MCP input/output schemas may declare the root `$schema` as exactly
|
|
142
|
+
`https://json-schema.org/draft/2020-12/schema`. The adapter recognizes this
|
|
143
|
+
MCP dialect declaration, retains it in the immutable snapshot and revision
|
|
144
|
+
digest, and compiles the remaining constraints with `purra.output-schema/v1`.
|
|
145
|
+
The full remote schema, including the declaration, counts against the schema
|
|
146
|
+
byte limit. Other dialect URIs, nested declarations, references, and unknown
|
|
147
|
+
keywords remain unsupported; no schema document is fetched. This does not add
|
|
148
|
+
`$schema` to the Core structured-output profile or promise full JSON Schema
|
|
149
|
+
2020-12 support. See the [MCP schema rules](https://modelcontextprotocol.io/specification/2025-11-25/server/tools).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/purra_mcp/__init__.py
|
|
5
|
+
src/purra_mcp.egg-info/PKG-INFO
|
|
6
|
+
src/purra_mcp.egg-info/SOURCES.txt
|
|
7
|
+
src/purra_mcp.egg-info/dependency_links.txt
|
|
8
|
+
src/purra_mcp.egg-info/requires.txt
|
|
9
|
+
src/purra_mcp.egg-info/top_level.txt
|
|
10
|
+
tests/test_protocol.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
purra_mcp
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from contextlib import asynccontextmanager
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from mcp import ClientSession, types
|
|
8
|
+
from mcp.server import Server
|
|
9
|
+
from mcp.shared.memory import create_client_server_memory_streams
|
|
10
|
+
from purra.cancellation import OperationCanceled
|
|
11
|
+
from purra.contracts import ExecutionState, ToolPolicy
|
|
12
|
+
from purra_mcp import McpAdapterError, McpCatalogMonitor, McpToolBinding, McpToolLimits, discover_mcp_tools
|
|
13
|
+
|
|
14
|
+
FIXTURE = json.loads((Path(__file__).parents[2] / 'fixtures/tools.json').read_text())
|
|
15
|
+
TOOL = FIXTURE['tool']
|
|
16
|
+
BINDING = McpToolBinding('search', ToolPolicy(mode='read', title='Search'), None, True)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ProtocolServer:
|
|
20
|
+
def __init__(self, pages=None, result=None, malformed=False):
|
|
21
|
+
self.server = Server('fixture')
|
|
22
|
+
self.pages = pages or [{'tools': [TOOL]}]
|
|
23
|
+
self.result = result or {'content': [], 'structuredContent': {'count': 1}}
|
|
24
|
+
self.lists = []
|
|
25
|
+
self.calls = []
|
|
26
|
+
self.started = asyncio.Event()
|
|
27
|
+
self.finished = asyncio.Event()
|
|
28
|
+
self.gate = None
|
|
29
|
+
self.changed = False
|
|
30
|
+
self.rpc_error = False
|
|
31
|
+
@self.server.list_tools()
|
|
32
|
+
async def list_tools(request: types.ListToolsRequest):
|
|
33
|
+
self.session = self.server.request_context.session
|
|
34
|
+
self.lists.append(request.params.cursor if request.params else None)
|
|
35
|
+
if self.changed:
|
|
36
|
+
await self.session.send_tool_list_changed()
|
|
37
|
+
return types.ListToolsResult(**self.pages[min(len(self.lists)-1, len(self.pages)-1)])
|
|
38
|
+
async def call_tool(request):
|
|
39
|
+
self.calls.append(request.params)
|
|
40
|
+
self.started.set()
|
|
41
|
+
try:
|
|
42
|
+
if self.gate is not None:
|
|
43
|
+
await self.gate.wait()
|
|
44
|
+
if self.rpc_error:
|
|
45
|
+
raise ValueError('private remote exception')
|
|
46
|
+
if malformed:
|
|
47
|
+
return types.ServerResult.model_construct(root=types.CallToolResult.model_construct(**self.result))
|
|
48
|
+
return types.ServerResult(types.CallToolResult(**self.result))
|
|
49
|
+
finally:
|
|
50
|
+
self.finished.set()
|
|
51
|
+
self.server.request_handlers[types.CallToolRequest] = call_tool
|
|
52
|
+
|
|
53
|
+
@asynccontextmanager
|
|
54
|
+
async def connect(self):
|
|
55
|
+
monitor = McpCatalogMonitor()
|
|
56
|
+
async with create_client_server_memory_streams() as (client_streams, server_streams):
|
|
57
|
+
self.server_write = server_streams[1]
|
|
58
|
+
running = asyncio.create_task(self.server.run(*server_streams, self.server.create_initialization_options()))
|
|
59
|
+
try:
|
|
60
|
+
async with ClientSession(*client_streams, message_handler=monitor.on_message) as client:
|
|
61
|
+
initialized = await client.initialize()
|
|
62
|
+
monitor.accept_protocol_version(initialized.protocolVersion)
|
|
63
|
+
yield client, monitor
|
|
64
|
+
finally:
|
|
65
|
+
monitor.close()
|
|
66
|
+
running.cancel()
|
|
67
|
+
await asyncio.gather(running, return_exceptions=True)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def discover(client, monitor, **kwargs):
|
|
71
|
+
return await discover_mcp_tools(client, 'fixture', {'remote.search': BINDING}, monitor=monitor, **kwargs)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@pytest.mark.asyncio
|
|
75
|
+
@pytest.mark.parametrize('row', FIXTURE['cases'], ids=lambda row: row['id'])
|
|
76
|
+
async def test_shared_result_boundary(row):
|
|
77
|
+
fixture = ProtocolServer(result=row['result'], malformed=row.get('malformed',False))
|
|
78
|
+
async with fixture.connect() as (client, monitor):
|
|
79
|
+
limits = McpToolLimits(**{'max_result_bytes' if k == 'maxResultBytes' else 'max_content_blocks': v for k,v in row.get('limits', {}).items()})
|
|
80
|
+
catalog = await discover(client, monitor, limits=limits)
|
|
81
|
+
result = await catalog.registrations[0].handler(ExecutionState(), row['arguments'])
|
|
82
|
+
assert result.error_code == row['errorCode']
|
|
83
|
+
assert len(fixture.lists) == 1 # No hidden call_tool cache refresh.
|
|
84
|
+
assert len(fixture.calls) == (0 if row['errorCode'] == 'mcp_invalid_arguments' else 1)
|
|
85
|
+
if row['errorCode'] is None:
|
|
86
|
+
assert json.loads(result.content) == {'text':[c['text'] for c in row['result']['content']], 'structured':row['result']['structuredContent']}
|
|
87
|
+
assert fixture.calls[0].arguments == row['arguments']
|
|
88
|
+
else:
|
|
89
|
+
assert json.loads(result.content) == {'text':[], 'structured':None}
|
|
90
|
+
await client.send_ping() # Adapter leaves host session open.
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@pytest.mark.asyncio
|
|
94
|
+
async def test_snapshot_allowlist_pagination_and_immutability():
|
|
95
|
+
other = {'name':'unbound','inputSchema':{'type':'object','$ref':'https://example.invalid/private'}}
|
|
96
|
+
fixture = ProtocolServer(pages=[{'tools':[other], 'nextCursor':'next'}, {'tools':[TOOL]}])
|
|
97
|
+
async with fixture.connect() as (client, monitor):
|
|
98
|
+
bindings = {'remote.search': BINDING}
|
|
99
|
+
catalog = await discover_mcp_tools(client, 'fixture', bindings, monitor=monitor)
|
|
100
|
+
bindings.clear()
|
|
101
|
+
assert fixture.lists == [None, 'next']
|
|
102
|
+
assert len(catalog.registrations) == 1
|
|
103
|
+
assert catalog.snapshot.entries[0]['policy']['mode'] == 'read'
|
|
104
|
+
assert catalog.registrations[0].concurrency_safe is True
|
|
105
|
+
with pytest.raises(TypeError):
|
|
106
|
+
catalog.snapshot.entries[0]['inputSchema']['required'][0] = 'other'
|
|
107
|
+
assert catalog.snapshot.revision_digest == FIXTURE['revisionDigest']
|
|
108
|
+
await fixture.session.send_tool_list_changed()
|
|
109
|
+
for _ in range(100):
|
|
110
|
+
if catalog.stale: break
|
|
111
|
+
await asyncio.sleep(0)
|
|
112
|
+
assert catalog.stale
|
|
113
|
+
result = await catalog.registrations[0].handler(ExecutionState(), {'q':'a'})
|
|
114
|
+
assert result.error_code == 'mcp_catalog_stale'
|
|
115
|
+
assert not fixture.calls
|
|
116
|
+
fresh = await discover(client, monitor)
|
|
117
|
+
assert not fresh.stale
|
|
118
|
+
assert fresh.snapshot.revision_digest == catalog.snapshot.revision_digest
|
|
119
|
+
monitor.close()
|
|
120
|
+
assert fresh.stale
|
|
121
|
+
await client.send_ping()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@pytest.mark.asyncio
|
|
125
|
+
@pytest.mark.parametrize('pages,code', [
|
|
126
|
+
([{'tools':[TOOL, TOOL]}], 'mcp_name_conflict'),
|
|
127
|
+
([{'tools':[], 'nextCursor':'again'}], 'mcp_pagination_invalid'),
|
|
128
|
+
([{'tools':[]}], 'mcp_binding_missing'),
|
|
129
|
+
([{'tools':[{**TOOL, 'inputSchema':{'type':'object','$ref':'#/$defs/x'}}]}], 'mcp_schema_unsupported'),
|
|
130
|
+
([{'tools':[{**TOOL, 'execution':{'taskSupport':'required'}}]}], 'mcp_tool_unsupported'),
|
|
131
|
+
])
|
|
132
|
+
async def test_catalog_rejections(pages, code):
|
|
133
|
+
fixture = ProtocolServer(pages=pages)
|
|
134
|
+
async with fixture.connect() as (client, monitor):
|
|
135
|
+
with pytest.raises(McpAdapterError) as error:
|
|
136
|
+
await discover(client, monitor)
|
|
137
|
+
assert error.value.code == code
|
|
138
|
+
assert not fixture.calls
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@pytest.mark.asyncio
|
|
142
|
+
async def test_preflight_policy_scope_and_stale_discovery():
|
|
143
|
+
fixture = ProtocolServer()
|
|
144
|
+
async with fixture.connect() as (client, monitor):
|
|
145
|
+
with pytest.raises(McpAdapterError):
|
|
146
|
+
McpToolBinding('write', ToolPolicy(mode='propose', title='Write'), None)
|
|
147
|
+
with pytest.raises(McpAdapterError) as error:
|
|
148
|
+
await discover_mcp_tools(client, 'fixture', {'remote.search': BINDING, 'other': BINDING}, monitor=monitor)
|
|
149
|
+
assert error.value.code == 'mcp_name_conflict'
|
|
150
|
+
assert not fixture.lists
|
|
151
|
+
async def deny(state, arguments, signal):
|
|
152
|
+
assert arguments['q'] == 'a'
|
|
153
|
+
return 'no access'
|
|
154
|
+
binding = McpToolBinding('search', ToolPolicy(mode='read', title='Search'), deny)
|
|
155
|
+
catalog = await discover_mcp_tools(client,'fixture',{'remote.search':binding},monitor=monitor)
|
|
156
|
+
assert (await catalog.registrations[0].handler(ExecutionState(), {'q':'a'})).error_code == 'mcp_scope_denied'
|
|
157
|
+
assert not fixture.calls
|
|
158
|
+
fixture.changed = True
|
|
159
|
+
with pytest.raises(McpAdapterError) as error:
|
|
160
|
+
await discover(client, monitor)
|
|
161
|
+
assert error.value.code == 'mcp_catalog_stale'
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@pytest.mark.asyncio
|
|
165
|
+
@pytest.mark.parametrize('mode', ['cancel','timeout','stale','rpc','disconnect'])
|
|
166
|
+
async def test_inflight_boundaries(mode):
|
|
167
|
+
fixture = ProtocolServer()
|
|
168
|
+
fixture.gate = asyncio.Event()
|
|
169
|
+
fixture.rpc_error = mode == 'rpc'
|
|
170
|
+
async with fixture.connect() as (client, monitor):
|
|
171
|
+
catalog = await discover(client, monitor, limits=McpToolLimits(timeout_ms=100 if mode == 'timeout' else 2000))
|
|
172
|
+
signal = asyncio.Event()
|
|
173
|
+
running = asyncio.create_task(catalog.registrations[0].handler(ExecutionState(), {'q':'a'}, signal))
|
|
174
|
+
await asyncio.wait_for(fixture.started.wait(), 1)
|
|
175
|
+
if mode == 'cancel': signal.set()
|
|
176
|
+
elif mode == 'stale':
|
|
177
|
+
await fixture.session.send_tool_list_changed()
|
|
178
|
+
while not catalog.stale: await asyncio.sleep(0)
|
|
179
|
+
fixture.gate.set()
|
|
180
|
+
elif mode == 'rpc': fixture.gate.set()
|
|
181
|
+
elif mode == 'disconnect': await fixture.server_write.aclose()
|
|
182
|
+
if mode == 'cancel':
|
|
183
|
+
with pytest.raises(OperationCanceled): await asyncio.wait_for(running, 1)
|
|
184
|
+
else:
|
|
185
|
+
result = await asyncio.wait_for(running, 2)
|
|
186
|
+
assert result.error_code == {'timeout':'mcp_timeout','stale':'mcp_catalog_stale','rpc':'mcp_protocol_error','disconnect':'mcp_transport_error'}[mode]
|
|
187
|
+
assert 'private' not in result.content
|
|
188
|
+
fixture.gate.set()
|
|
189
|
+
await asyncio.wait_for(fixture.finished.wait(), 1)
|
|
190
|
+
assert len(fixture.calls) == 1
|
|
191
|
+
if mode != 'disconnect': await client.send_ping()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@pytest.mark.asyncio
|
|
195
|
+
async def test_core_executor_strict_admission_before_any_remote_call():
|
|
196
|
+
from purra.contracts import ToolBatchRequest, ToolCall
|
|
197
|
+
from purra.tools import CoreToolExecutor, InMemoryToolCatalog
|
|
198
|
+
fixture = ProtocolServer()
|
|
199
|
+
async with fixture.connect() as (client, monitor):
|
|
200
|
+
catalog = await discover(client, monitor)
|
|
201
|
+
executor = CoreToolExecutor(InMemoryToolCatalog(catalog.registrations))
|
|
202
|
+
class Sink:
|
|
203
|
+
async def emit(self, event): pass
|
|
204
|
+
sink = Sink()
|
|
205
|
+
def batch(calls):
|
|
206
|
+
return ToolBatchRequest('run',tuple(ToolCall(str(i),'search',args) for i,args in enumerate(calls)),frozenset({'search'}),ExecutionState())
|
|
207
|
+
for invalid in ['{"q":"a","tags":"[\\"x\\"]"}', '{"q":"a","q":"b"}']:
|
|
208
|
+
result = await executor.execute_batch(batch(['{"q":"a"}',invalid]),sink)
|
|
209
|
+
assert result.outcome.value == 'failed'
|
|
210
|
+
assert all(row.error == 'invalid_tool_arguments_schema' for row in result.results)
|
|
211
|
+
assert not fixture.calls
|
|
212
|
+
result = await executor.execute_batch(batch(['{"q":"😀","n":1.0}']),sink)
|
|
213
|
+
assert result.outcome.value == 'completed'
|
|
214
|
+
assert len(fixture.calls) == 1
|
|
215
|
+
assert fixture.calls[0].arguments == {'q':'😀','n':1}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
@pytest.mark.asyncio
|
|
219
|
+
@pytest.mark.parametrize('limit', [McpToolLimits(max_pages=1), McpToolLimits(max_tools=1), McpToolLimits(max_catalog_bytes=64), McpToolLimits(max_description_bytes=1)])
|
|
220
|
+
async def test_catalog_capacity_is_bounded(limit):
|
|
221
|
+
pages = [{'tools':[TOOL], 'nextCursor':'next'}, {'tools':[{'name':'other','inputSchema':{'type':'object'}}]}]
|
|
222
|
+
fixture = ProtocolServer(pages=pages)
|
|
223
|
+
async with fixture.connect() as (client, monitor):
|
|
224
|
+
with pytest.raises(McpAdapterError) as error:
|
|
225
|
+
await discover(client, monitor, limits=limit)
|
|
226
|
+
assert error.value.code == 'mcp_catalog_limit_exceeded'
|
|
227
|
+
assert len(fixture.lists) <= 2
|
|
228
|
+
assert not fixture.calls
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@pytest.mark.asyncio
|
|
232
|
+
async def test_cancel_before_discovery_and_call_does_no_io():
|
|
233
|
+
fixture = ProtocolServer()
|
|
234
|
+
async with fixture.connect() as (client, monitor):
|
|
235
|
+
signal = asyncio.Event(); signal.set()
|
|
236
|
+
with pytest.raises(OperationCanceled):
|
|
237
|
+
await discover(client, monitor, signal=signal)
|
|
238
|
+
assert not fixture.lists
|
|
239
|
+
catalog = await discover(client, monitor)
|
|
240
|
+
with pytest.raises(OperationCanceled):
|
|
241
|
+
await catalog.registrations[0].handler(ExecutionState(), {'q':'a'}, signal)
|
|
242
|
+
assert not fixture.calls
|
|
243
|
+
monitor.close()
|
|
244
|
+
with pytest.raises(McpAdapterError) as error:
|
|
245
|
+
await discover(client, monitor)
|
|
246
|
+
assert error.value.code == 'mcp_connection_closed'
|
|
247
|
+
assert len(fixture.lists) == 1
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def test_unknown_negotiated_protocol_rejected():
|
|
251
|
+
monitor = McpCatalogMonitor()
|
|
252
|
+
with pytest.raises(McpAdapterError) as error:
|
|
253
|
+
monitor.accept_protocol_version('2099-01-01')
|
|
254
|
+
assert error.value.code == 'mcp_protocol_unsupported'
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
@pytest.mark.asyncio
|
|
258
|
+
async def test_snapshot_identity_tracks_selected_contract_not_discovery_order():
|
|
259
|
+
other = {**TOOL, 'name':'remote.other'}
|
|
260
|
+
bindings = {'remote.search':BINDING,'remote.other':McpToolBinding('another',ToolPolicy(mode='read',title='Other'),None)}
|
|
261
|
+
digests = []
|
|
262
|
+
for tools in ([TOOL,other],[other,TOOL],[other,{**TOOL,'description':'Changed description'}]):
|
|
263
|
+
fixture = ProtocolServer(pages=[{'tools':tools}])
|
|
264
|
+
async with fixture.connect() as (client, monitor):
|
|
265
|
+
catalog = await discover_mcp_tools(client,'fixture',bindings,monitor=monitor)
|
|
266
|
+
assert [entry['localName'] for entry in catalog.snapshot.entries] == ['another','search']
|
|
267
|
+
digests.append(catalog.snapshot.revision_digest)
|
|
268
|
+
assert digests[0] == digests[1]
|
|
269
|
+
assert digests[1] != digests[2]
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@pytest.mark.asyncio
|
|
273
|
+
async def test_text_only_tool_does_not_guess_structured_json():
|
|
274
|
+
fixture = ProtocolServer(pages=[{'tools':[{key:value for key,value in TOOL.items() if key != 'outputSchema'}]}],
|
|
275
|
+
result={'content':[{'type':'text','text':'{"count":3}'}]})
|
|
276
|
+
async with fixture.connect() as (client, monitor):
|
|
277
|
+
result = await (await discover(client,monitor)).registrations[0].handler(ExecutionState(),{'q':'a'})
|
|
278
|
+
assert result.error_code is None
|
|
279
|
+
assert json.loads(result.content) == {'text':['{"count":3}'],'structured':None}
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
@pytest.mark.asyncio
|
|
283
|
+
async def test_core_parallel_calls_share_one_host_session():
|
|
284
|
+
from purra.contracts import ToolBatchRequest, ToolCall, ToolExecutionLimits
|
|
285
|
+
from purra.tools import CoreToolExecutor, InMemoryToolCatalog
|
|
286
|
+
fixture = ProtocolServer(); fixture.gate = asyncio.Event()
|
|
287
|
+
async with fixture.connect() as (client,monitor):
|
|
288
|
+
catalog = await discover(client,monitor)
|
|
289
|
+
executor = CoreToolExecutor(InMemoryToolCatalog(catalog.registrations),limits=ToolExecutionLimits(max_concurrency=2))
|
|
290
|
+
class Sink:
|
|
291
|
+
async def emit(self,event): pass
|
|
292
|
+
request = ToolBatchRequest('parallel',tuple(ToolCall(str(i),'search',json.dumps({'q':str(i)})) for i in range(3)),frozenset({'search'}),ExecutionState())
|
|
293
|
+
running = asyncio.create_task(executor.execute_batch(request,Sink()))
|
|
294
|
+
async def two_calls():
|
|
295
|
+
while len(fixture.calls)<2: await asyncio.sleep(0)
|
|
296
|
+
await asyncio.wait_for(two_calls(),1)
|
|
297
|
+
assert len(fixture.calls)==2
|
|
298
|
+
fixture.gate.set()
|
|
299
|
+
result = await asyncio.wait_for(running,1)
|
|
300
|
+
assert result.outcome.value=='completed'
|
|
301
|
+
assert [r.tool_call_id for r in result.results]==['0','1','2']
|
|
302
|
+
assert len(fixture.lists)==1 and len(fixture.calls)==3
|
|
303
|
+
|
|
304
|
+
@pytest.mark.asyncio
|
|
305
|
+
@pytest.mark.parametrize('row', FIXTURE['schemaCases'], ids=lambda row: row['id'])
|
|
306
|
+
async def test_selected_schema_metadata_is_not_silently_discarded(row):
|
|
307
|
+
fixture = ProtocolServer(pages=[{'tools': [row['tool']]}])
|
|
308
|
+
async with fixture.connect() as (client, monitor):
|
|
309
|
+
with pytest.raises(McpAdapterError) as caught:
|
|
310
|
+
await discover(client, monitor)
|
|
311
|
+
assert caught.value.code == row['errorCode']
|
|
312
|
+
assert fixture.calls == []
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
@pytest.mark.asyncio
|
|
316
|
+
async def test_declared_dialect_keeps_snapshot_identity_and_argument_validation():
|
|
317
|
+
fixture = ProtocolServer(pages=[{'tools':[FIXTURE['declaredDialectTool']]}])
|
|
318
|
+
async with fixture.connect() as (client, monitor):
|
|
319
|
+
catalog = await discover(client, monitor)
|
|
320
|
+
for key in ('inputSchema','outputSchema'):
|
|
321
|
+
assert catalog.snapshot.entries[0][key]['$schema'] == FIXTURE['declaredDialectTool'][key]['$schema']
|
|
322
|
+
assert '$schema' not in catalog.registrations[0].argument_contract.schema
|
|
323
|
+
denied = await catalog.registrations[0].handler(ExecutionState(), {'q':'too long'})
|
|
324
|
+
assert denied.error_code == 'mcp_invalid_arguments'
|
|
325
|
+
assert not fixture.calls
|
|
326
|
+
result = await catalog.registrations[0].handler(ExecutionState(), {'q':'a'})
|
|
327
|
+
assert result.error_code is None
|
|
328
|
+
assert json.loads(result.content)['structured'] == {'count':1}
|
|
329
|
+
assert len(fixture.calls) == 1
|
|
330
|
+
async with ProtocolServer().connect() as (client, monitor):
|
|
331
|
+
assert (await discover(client, monitor)).snapshot.revision_digest != catalog.snapshot.revision_digest
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
@pytest.mark.asyncio
|
|
335
|
+
async def test_declared_output_dialect_still_rejects_wrong_result():
|
|
336
|
+
fixture = ProtocolServer(pages=[{'tools':[FIXTURE['declaredDialectTool']]}], result={'content':[],'structuredContent':{'count':'wrong'}})
|
|
337
|
+
async with fixture.connect() as (client, monitor):
|
|
338
|
+
result = await (await discover(client,monitor)).registrations[0].handler(ExecutionState(), {'q':'a'})
|
|
339
|
+
assert result.error_code == 'mcp_result_invalid'
|
|
340
|
+
assert len(fixture.calls) == 1
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
@pytest.mark.asyncio
|
|
344
|
+
async def test_schema_byte_limit_includes_dialect_declaration():
|
|
345
|
+
tool = {'name':'remote.search','inputSchema':{'type':'object','$schema':'https://json-schema.org/draft/2020-12/schema'}}
|
|
346
|
+
async with ProtocolServer(pages=[{'tools':[tool]}]).connect() as (client, monitor):
|
|
347
|
+
with pytest.raises(McpAdapterError) as caught:
|
|
348
|
+
await discover(client,monitor,limits=McpToolLimits(max_schema_bytes=60))
|
|
349
|
+
assert caught.value.code == 'mcp_schema_unsupported'
|