prism-ai-mcp-server 0.2.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.
- prism_ai_mcp_server-0.2.0/.gitignore +8 -0
- prism_ai_mcp_server-0.2.0/LICENSE +21 -0
- prism_ai_mcp_server-0.2.0/PKG-INFO +174 -0
- prism_ai_mcp_server-0.2.0/README.md +160 -0
- prism_ai_mcp_server-0.2.0/pyproject.toml +35 -0
- prism_ai_mcp_server-0.2.0/src/prism_mcp_server/__init__.py +487 -0
- prism_ai_mcp_server-0.2.0/src/prism_mcp_server/http.py +361 -0
- prism_ai_mcp_server-0.2.0/src/prism_mcp_server/py.typed +0 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Particle Academy
|
|
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.
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: prism-ai-mcp-server
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Transport-independent MCP tool serving for the Prism ecosystem.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: prism-ai-mcp==0.3.0
|
|
9
|
+
Provides-Extra: dev
|
|
10
|
+
Requires-Dist: mypy>=1.11; extra == 'dev'
|
|
11
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
12
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# prism-ai-mcp-server
|
|
16
|
+
|
|
17
|
+
MCP tool registration and dispatch over a consumer-supplied
|
|
18
|
+
`ServerTransport`, with in-memory and authenticated loopback HTTP implementations.
|
|
19
|
+
Python 3.10+, typed module `prism_mcp_server`. No stdio, sessions, push,
|
|
20
|
+
resources or prompts.
|
|
21
|
+
|
|
22
|
+
Both protocols are served on the same transport and the same tool registry:
|
|
23
|
+
|
|
24
|
+
- **Stateless** (`2026-07-28`): `server/discover`, then `tools/list` and
|
|
25
|
+
`tools/call`, each carrying its version and client capabilities in
|
|
26
|
+
`params._meta`.
|
|
27
|
+
- **Handshake** (`2025-11-25`, `2025-06-18`, `2025-03-26`, `2024-11-05`):
|
|
28
|
+
`initialize`, `notifications/initialized` (answered 202), `ping`,
|
|
29
|
+
`tools/list` and `tools/call`, for clients that always open with
|
|
30
|
+
`initialize`, such as Codex. No session id is issued, so every request
|
|
31
|
+
stands alone. An unknown requested revision is answered with `2025-11-25`.
|
|
32
|
+
|
|
33
|
+
A request carrying any stateless `_meta` key is held to the stateless rules.
|
|
34
|
+
Bearer and Origin checks, the gate and the result guard apply to both
|
|
35
|
+
protocols in the same way. `SUPPORTED_PROTOCOL_VERSIONS` lists every version
|
|
36
|
+
served, newest first, and `protocol-versions.json` publishes the same list.
|
|
37
|
+
|
|
38
|
+
`Server(..., instructions="...")` sets the server's `instructions`: guidance a
|
|
39
|
+
client may give its model, sent in the `initialize` and `server/discover`
|
|
40
|
+
results. Because it reaches the model, it comes only from your own
|
|
41
|
+
configuration, fixed at construction; no request can set it. It must be a
|
|
42
|
+
non-empty string of at most 16 KiB.
|
|
43
|
+
|
|
44
|
+
The sole runtime dependency is `prism-ai-mcp`; there are **zero third-party
|
|
45
|
+
runtime dependencies**. Shared definitions/errors/guards come from `prism_mcp`.
|
|
46
|
+
Python keeps the existing names `ErrorCode` and `ToolResult`. The local
|
|
47
|
+
`JsonObject = dict[str, Any]` alias adds no runtime behavior. The official `mcp`
|
|
48
|
+
SDK is in the dev extra only, reserved for phase 3 reference-client tests;
|
|
49
|
+
production code does not import it.
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from prism_mcp import ToolDefinition, ToolResult
|
|
53
|
+
from prism_mcp_server import InMemoryTransport, JsonObject, Server, ToolContext
|
|
54
|
+
|
|
55
|
+
transport = InMemoryTransport()
|
|
56
|
+
server = Server("example", transport)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def echo(args: JsonObject, context: ToolContext) -> ToolResult:
|
|
60
|
+
return ToolResult(str(args.get("text", "")))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
server.register(
|
|
64
|
+
ToolDefinition(
|
|
65
|
+
"echo",
|
|
66
|
+
"Echo text",
|
|
67
|
+
{
|
|
68
|
+
"type": "object",
|
|
69
|
+
"properties": {"text": {"type": "string"}},
|
|
70
|
+
},
|
|
71
|
+
),
|
|
72
|
+
echo,
|
|
73
|
+
)
|
|
74
|
+
# Inside your event loop: await server.listen(), await transport.request(...),
|
|
75
|
+
# then await server.close(). Synchronous and awaitable handlers are accepted.
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Handlers take arguments plus `{server, tool, headers}` context and return the
|
|
79
|
+
shared `ToolResult`. Registration snapshots definitions; duplicate names fail.
|
|
80
|
+
Invalid mirrored annotations raise `mirrored_parameter_refused`, disappear from
|
|
81
|
+
`tools/list`, and cannot run. Listed definitions preserve the client's digest.
|
|
82
|
+
|
|
83
|
+
`ToolGate` defaults to **allow_all on the server**, unlike the client's
|
|
84
|
+
deny-by-default trust posture. Registration explicitly chooses what is served;
|
|
85
|
+
an embedder's custom gate may refuse calls before handlers run. `TrustPolicy`
|
|
86
|
+
does not apply inbound. Default outbound `ResultGuard` caps UTF-8 text at 64 KiB
|
|
87
|
+
for both success and `is_error` results, without provenance framing; clients
|
|
88
|
+
apply that framing once. Custom guards can intentionally transform text.
|
|
89
|
+
|
|
90
|
+
Server gates may return a boolean or an awaitable boolean. The asynchronous
|
|
91
|
+
server awaits the verdict before permitting execution; `async def` returning
|
|
92
|
+
`False` refuses the call. The sibling Python client's synchronous API is unchanged.
|
|
93
|
+
|
|
94
|
+
Only `Mcp-Param-*` headers reach handlers. The prefix is required and stripped
|
|
95
|
+
case-insensitively; context keys are lowercase. Raw `Authorization`, `Cookie`,
|
|
96
|
+
`Origin` and other unnamespaced headers stay private. Shared
|
|
97
|
+
`MirroredParameters` resolve nested string/integer/boolean fields into arguments
|
|
98
|
+
before the gate. Conflicting body/header values, ambiguous headers and invalid
|
|
99
|
+
primitive encodings are refused. Integers use the shared JS-safe range for
|
|
100
|
+
cross-language agreement. Other application argument validation belongs to handlers.
|
|
101
|
+
|
|
102
|
+
`tools/list` and `tools/call` require `params['_meta']` with
|
|
103
|
+
`io.modelcontextprotocol/protocolVersion: '2026-07-28'`,
|
|
104
|
+
`io.modelcontextprotocol/clientCapabilities: {}`.
|
|
105
|
+
`io.modelcontextprotocol/clientInfo: {name: 'example', version: '1'}` is optional.
|
|
106
|
+
Older revisions raise shared `unsupported_protocol_version`, naming both
|
|
107
|
+
revisions. `server/discover`, `tools/list` and `tools/call` are supported.
|
|
108
|
+
Discovery advertises `supportedVersions: ['2026-07-28']` and `capabilities: {tools: {}}`
|
|
109
|
+
regardless of the probe's requested version, including absent, older or unknown
|
|
110
|
+
versions. The probe needs no `params`, `_meta`, capabilities or client identity,
|
|
111
|
+
creates no session, and does not change server state. It uses the same
|
|
112
|
+
HTTP bearer and Origin checks as tool requests. Every successful result includes
|
|
113
|
+
`resultType: 'complete'` and `_meta['io.modelcontextprotocol/serverInfo']` identifying
|
|
114
|
+
the serving software as `{name: 'prism-ai-mcp-server', version: '0.1.0'}`.
|
|
115
|
+
Discovery and tool lists include `ttlMs: 0, cacheScope: 'private'`; callers re-fetch
|
|
116
|
+
to observe registration changes. Tool call results also carry
|
|
117
|
+
`{content: [{type: 'text', text: ...}], isError: ...}`; failures raise shared
|
|
118
|
+
`McpError` for transport mapping. Arbitrary handler diagnostic messages are
|
|
119
|
+
excluded; a shared error category is retained.
|
|
120
|
+
|
|
121
|
+
In-memory `listen()` returns a `memory://` identifier and `token: None`, not HTTP
|
|
122
|
+
credentials or a dialable URL. Requests have no fixed timeout. `close()` releases
|
|
123
|
+
pending request waiters, rejects further requests and is idempotent. Cancellation
|
|
124
|
+
of handler-owned work is best-effort; an embedder must clean up application work
|
|
125
|
+
that suppresses cancellation. SDK conformance and consumer acceptance remain phase 3.
|
|
126
|
+
|
|
127
|
+
For HTTP, replace the transport with `LoopbackHttpTransport()`:
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from prism_mcp_server import LoopbackHttpTransport, Server
|
|
131
|
+
|
|
132
|
+
transport = LoopbackHttpTransport()
|
|
133
|
+
server = Server("example", transport)
|
|
134
|
+
# Register application tools. Inside your event loop:
|
|
135
|
+
# endpoint = await server.listen()
|
|
136
|
+
# Give endpoint["url"] and endpoint["token"] privately to the client.
|
|
137
|
+
# Each POST needs Authorization: Bearer <token> and Content-Type: application/json.
|
|
138
|
+
# Send JSON-RPC 2.0 with id, method and the per-request params["_meta"] above.
|
|
139
|
+
# await server.close() when the embedder shuts down.
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
The HTTP URL is `http://127.0.0.1:<port>/mcp`. `port` defaults to `0` (an OS-chosen
|
|
143
|
+
port); the bind address is fixed to literal `127.0.0.1`. `token` is generated at
|
|
144
|
+
startup with `secrets.token_hex(32)`, or may be supplied as a keyword argument.
|
|
145
|
+
Configured tokens must be non-empty bearer-token strings; whitespace is refused
|
|
146
|
+
before listening. HTTP always returns a real token; only memory returns `None`.
|
|
147
|
+
The URL alone does not authorize a client. Keep the token out of URLs and logs.
|
|
148
|
+
Every request requires `Authorization: Bearer <token>`; comparison uses fixed-size
|
|
149
|
+
SHA-256 digests and `hmac.compare_digest`.
|
|
150
|
+
|
|
151
|
+
Requests without `Origin` may proceed with valid credentials. A browser `Origin`
|
|
152
|
+
must exactly match the listener's own origin by default. `allowed_origins` replaces
|
|
153
|
+
that allow-list with explicit `http://127.0.0.1:<port>` / `https://[::1]:<port>`
|
|
154
|
+
origins (either scheme is supported); arbitrary hostnames, paths, wildcard origins
|
|
155
|
+
and non-loopback addresses are refused at startup. No browser CORS/preflight
|
|
156
|
+
support is provided. GET, upgrades, CONNECT and SSE-only requests are refused;
|
|
157
|
+
an Accept header offering both JSON and SSE receives JSON.
|
|
158
|
+
|
|
159
|
+
POSTs require `Content-Length` and JSON content; chunked uploads, batches,
|
|
160
|
+
notifications and ambiguous duplicate headers are refused. `max_request_bytes`
|
|
161
|
+
defaults to 1 MiB. Responses carry the same request id and either `result` or a
|
|
162
|
+
JSON-RPC `error` with the shared Prism category in `error.data.code`; arbitrary
|
|
163
|
+
diagnostic messages are withheld. HTTP refusal uses 401 for credentials and 403
|
|
164
|
+
for Origin. There is no fixed request or socket timeout. The stdlib HTTP listener
|
|
165
|
+
uses daemon threads for HTTP I/O; registered handlers run on the calling asyncio
|
|
166
|
+
loop. `close()` releases every socket, including incomplete headers and held
|
|
167
|
+
long-polls, before resolving. Application cancellation remains best-effort.
|
|
168
|
+
|
|
169
|
+
Local setup: create a virtual environment and install `-e .[dev]` against the
|
|
170
|
+
published sibling dependency. Gates: `python -m pytest`, `python -m mypy --strict src tests`,
|
|
171
|
+
`python -m ruff check .`, `python -m ruff format --check .`.
|
|
172
|
+
No remote, publishing workflow or tag is configured here.
|
|
173
|
+
The complete suite includes a real 310-second HTTP long-poll and takes about
|
|
174
|
+
six minutes. SDK reference-client conformance is not part of this phase.
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# prism-ai-mcp-server
|
|
2
|
+
|
|
3
|
+
MCP tool registration and dispatch over a consumer-supplied
|
|
4
|
+
`ServerTransport`, with in-memory and authenticated loopback HTTP implementations.
|
|
5
|
+
Python 3.10+, typed module `prism_mcp_server`. No stdio, sessions, push,
|
|
6
|
+
resources or prompts.
|
|
7
|
+
|
|
8
|
+
Both protocols are served on the same transport and the same tool registry:
|
|
9
|
+
|
|
10
|
+
- **Stateless** (`2026-07-28`): `server/discover`, then `tools/list` and
|
|
11
|
+
`tools/call`, each carrying its version and client capabilities in
|
|
12
|
+
`params._meta`.
|
|
13
|
+
- **Handshake** (`2025-11-25`, `2025-06-18`, `2025-03-26`, `2024-11-05`):
|
|
14
|
+
`initialize`, `notifications/initialized` (answered 202), `ping`,
|
|
15
|
+
`tools/list` and `tools/call`, for clients that always open with
|
|
16
|
+
`initialize`, such as Codex. No session id is issued, so every request
|
|
17
|
+
stands alone. An unknown requested revision is answered with `2025-11-25`.
|
|
18
|
+
|
|
19
|
+
A request carrying any stateless `_meta` key is held to the stateless rules.
|
|
20
|
+
Bearer and Origin checks, the gate and the result guard apply to both
|
|
21
|
+
protocols in the same way. `SUPPORTED_PROTOCOL_VERSIONS` lists every version
|
|
22
|
+
served, newest first, and `protocol-versions.json` publishes the same list.
|
|
23
|
+
|
|
24
|
+
`Server(..., instructions="...")` sets the server's `instructions`: guidance a
|
|
25
|
+
client may give its model, sent in the `initialize` and `server/discover`
|
|
26
|
+
results. Because it reaches the model, it comes only from your own
|
|
27
|
+
configuration, fixed at construction; no request can set it. It must be a
|
|
28
|
+
non-empty string of at most 16 KiB.
|
|
29
|
+
|
|
30
|
+
The sole runtime dependency is `prism-ai-mcp`; there are **zero third-party
|
|
31
|
+
runtime dependencies**. Shared definitions/errors/guards come from `prism_mcp`.
|
|
32
|
+
Python keeps the existing names `ErrorCode` and `ToolResult`. The local
|
|
33
|
+
`JsonObject = dict[str, Any]` alias adds no runtime behavior. The official `mcp`
|
|
34
|
+
SDK is in the dev extra only, reserved for phase 3 reference-client tests;
|
|
35
|
+
production code does not import it.
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from prism_mcp import ToolDefinition, ToolResult
|
|
39
|
+
from prism_mcp_server import InMemoryTransport, JsonObject, Server, ToolContext
|
|
40
|
+
|
|
41
|
+
transport = InMemoryTransport()
|
|
42
|
+
server = Server("example", transport)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def echo(args: JsonObject, context: ToolContext) -> ToolResult:
|
|
46
|
+
return ToolResult(str(args.get("text", "")))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
server.register(
|
|
50
|
+
ToolDefinition(
|
|
51
|
+
"echo",
|
|
52
|
+
"Echo text",
|
|
53
|
+
{
|
|
54
|
+
"type": "object",
|
|
55
|
+
"properties": {"text": {"type": "string"}},
|
|
56
|
+
},
|
|
57
|
+
),
|
|
58
|
+
echo,
|
|
59
|
+
)
|
|
60
|
+
# Inside your event loop: await server.listen(), await transport.request(...),
|
|
61
|
+
# then await server.close(). Synchronous and awaitable handlers are accepted.
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Handlers take arguments plus `{server, tool, headers}` context and return the
|
|
65
|
+
shared `ToolResult`. Registration snapshots definitions; duplicate names fail.
|
|
66
|
+
Invalid mirrored annotations raise `mirrored_parameter_refused`, disappear from
|
|
67
|
+
`tools/list`, and cannot run. Listed definitions preserve the client's digest.
|
|
68
|
+
|
|
69
|
+
`ToolGate` defaults to **allow_all on the server**, unlike the client's
|
|
70
|
+
deny-by-default trust posture. Registration explicitly chooses what is served;
|
|
71
|
+
an embedder's custom gate may refuse calls before handlers run. `TrustPolicy`
|
|
72
|
+
does not apply inbound. Default outbound `ResultGuard` caps UTF-8 text at 64 KiB
|
|
73
|
+
for both success and `is_error` results, without provenance framing; clients
|
|
74
|
+
apply that framing once. Custom guards can intentionally transform text.
|
|
75
|
+
|
|
76
|
+
Server gates may return a boolean or an awaitable boolean. The asynchronous
|
|
77
|
+
server awaits the verdict before permitting execution; `async def` returning
|
|
78
|
+
`False` refuses the call. The sibling Python client's synchronous API is unchanged.
|
|
79
|
+
|
|
80
|
+
Only `Mcp-Param-*` headers reach handlers. The prefix is required and stripped
|
|
81
|
+
case-insensitively; context keys are lowercase. Raw `Authorization`, `Cookie`,
|
|
82
|
+
`Origin` and other unnamespaced headers stay private. Shared
|
|
83
|
+
`MirroredParameters` resolve nested string/integer/boolean fields into arguments
|
|
84
|
+
before the gate. Conflicting body/header values, ambiguous headers and invalid
|
|
85
|
+
primitive encodings are refused. Integers use the shared JS-safe range for
|
|
86
|
+
cross-language agreement. Other application argument validation belongs to handlers.
|
|
87
|
+
|
|
88
|
+
`tools/list` and `tools/call` require `params['_meta']` with
|
|
89
|
+
`io.modelcontextprotocol/protocolVersion: '2026-07-28'`,
|
|
90
|
+
`io.modelcontextprotocol/clientCapabilities: {}`.
|
|
91
|
+
`io.modelcontextprotocol/clientInfo: {name: 'example', version: '1'}` is optional.
|
|
92
|
+
Older revisions raise shared `unsupported_protocol_version`, naming both
|
|
93
|
+
revisions. `server/discover`, `tools/list` and `tools/call` are supported.
|
|
94
|
+
Discovery advertises `supportedVersions: ['2026-07-28']` and `capabilities: {tools: {}}`
|
|
95
|
+
regardless of the probe's requested version, including absent, older or unknown
|
|
96
|
+
versions. The probe needs no `params`, `_meta`, capabilities or client identity,
|
|
97
|
+
creates no session, and does not change server state. It uses the same
|
|
98
|
+
HTTP bearer and Origin checks as tool requests. Every successful result includes
|
|
99
|
+
`resultType: 'complete'` and `_meta['io.modelcontextprotocol/serverInfo']` identifying
|
|
100
|
+
the serving software as `{name: 'prism-ai-mcp-server', version: '0.1.0'}`.
|
|
101
|
+
Discovery and tool lists include `ttlMs: 0, cacheScope: 'private'`; callers re-fetch
|
|
102
|
+
to observe registration changes. Tool call results also carry
|
|
103
|
+
`{content: [{type: 'text', text: ...}], isError: ...}`; failures raise shared
|
|
104
|
+
`McpError` for transport mapping. Arbitrary handler diagnostic messages are
|
|
105
|
+
excluded; a shared error category is retained.
|
|
106
|
+
|
|
107
|
+
In-memory `listen()` returns a `memory://` identifier and `token: None`, not HTTP
|
|
108
|
+
credentials or a dialable URL. Requests have no fixed timeout. `close()` releases
|
|
109
|
+
pending request waiters, rejects further requests and is idempotent. Cancellation
|
|
110
|
+
of handler-owned work is best-effort; an embedder must clean up application work
|
|
111
|
+
that suppresses cancellation. SDK conformance and consumer acceptance remain phase 3.
|
|
112
|
+
|
|
113
|
+
For HTTP, replace the transport with `LoopbackHttpTransport()`:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from prism_mcp_server import LoopbackHttpTransport, Server
|
|
117
|
+
|
|
118
|
+
transport = LoopbackHttpTransport()
|
|
119
|
+
server = Server("example", transport)
|
|
120
|
+
# Register application tools. Inside your event loop:
|
|
121
|
+
# endpoint = await server.listen()
|
|
122
|
+
# Give endpoint["url"] and endpoint["token"] privately to the client.
|
|
123
|
+
# Each POST needs Authorization: Bearer <token> and Content-Type: application/json.
|
|
124
|
+
# Send JSON-RPC 2.0 with id, method and the per-request params["_meta"] above.
|
|
125
|
+
# await server.close() when the embedder shuts down.
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
The HTTP URL is `http://127.0.0.1:<port>/mcp`. `port` defaults to `0` (an OS-chosen
|
|
129
|
+
port); the bind address is fixed to literal `127.0.0.1`. `token` is generated at
|
|
130
|
+
startup with `secrets.token_hex(32)`, or may be supplied as a keyword argument.
|
|
131
|
+
Configured tokens must be non-empty bearer-token strings; whitespace is refused
|
|
132
|
+
before listening. HTTP always returns a real token; only memory returns `None`.
|
|
133
|
+
The URL alone does not authorize a client. Keep the token out of URLs and logs.
|
|
134
|
+
Every request requires `Authorization: Bearer <token>`; comparison uses fixed-size
|
|
135
|
+
SHA-256 digests and `hmac.compare_digest`.
|
|
136
|
+
|
|
137
|
+
Requests without `Origin` may proceed with valid credentials. A browser `Origin`
|
|
138
|
+
must exactly match the listener's own origin by default. `allowed_origins` replaces
|
|
139
|
+
that allow-list with explicit `http://127.0.0.1:<port>` / `https://[::1]:<port>`
|
|
140
|
+
origins (either scheme is supported); arbitrary hostnames, paths, wildcard origins
|
|
141
|
+
and non-loopback addresses are refused at startup. No browser CORS/preflight
|
|
142
|
+
support is provided. GET, upgrades, CONNECT and SSE-only requests are refused;
|
|
143
|
+
an Accept header offering both JSON and SSE receives JSON.
|
|
144
|
+
|
|
145
|
+
POSTs require `Content-Length` and JSON content; chunked uploads, batches,
|
|
146
|
+
notifications and ambiguous duplicate headers are refused. `max_request_bytes`
|
|
147
|
+
defaults to 1 MiB. Responses carry the same request id and either `result` or a
|
|
148
|
+
JSON-RPC `error` with the shared Prism category in `error.data.code`; arbitrary
|
|
149
|
+
diagnostic messages are withheld. HTTP refusal uses 401 for credentials and 403
|
|
150
|
+
for Origin. There is no fixed request or socket timeout. The stdlib HTTP listener
|
|
151
|
+
uses daemon threads for HTTP I/O; registered handlers run on the calling asyncio
|
|
152
|
+
loop. `close()` releases every socket, including incomplete headers and held
|
|
153
|
+
long-polls, before resolving. Application cancellation remains best-effort.
|
|
154
|
+
|
|
155
|
+
Local setup: create a virtual environment and install `-e .[dev]` against the
|
|
156
|
+
published sibling dependency. Gates: `python -m pytest`, `python -m mypy --strict src tests`,
|
|
157
|
+
`python -m ruff check .`, `python -m ruff format --check .`.
|
|
158
|
+
No remote, publishing workflow or tag is configured here.
|
|
159
|
+
The complete suite includes a real 310-second HTTP long-poll and takes about
|
|
160
|
+
six minutes. SDK reference-client conformance is not part of this phase.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "prism-ai-mcp-server"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Transport-independent MCP tool serving for the Prism ecosystem."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = ["prism-ai-mcp==0.3.0"]
|
|
14
|
+
|
|
15
|
+
[project.optional-dependencies]
|
|
16
|
+
dev = ["pytest>=8.0", "mypy>=1.11", "ruff>=0.6"]
|
|
17
|
+
|
|
18
|
+
[tool.hatch.build.targets.wheel]
|
|
19
|
+
packages = ["src/prism_mcp_server"]
|
|
20
|
+
|
|
21
|
+
[tool.hatch.build.targets.sdist]
|
|
22
|
+
include = ["/src/prism_mcp_server", "/README.md", "/LICENSE", "/pyproject.toml"]
|
|
23
|
+
|
|
24
|
+
[tool.pytest.ini_options]
|
|
25
|
+
testpaths = ["tests"]
|
|
26
|
+
pythonpath = ["src"]
|
|
27
|
+
|
|
28
|
+
[tool.ruff]
|
|
29
|
+
line-length = 100
|
|
30
|
+
target-version = "py310"
|
|
31
|
+
|
|
32
|
+
[tool.mypy]
|
|
33
|
+
python_version = "3.10"
|
|
34
|
+
strict = true
|
|
35
|
+
files = ["src", "tests"]
|
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
"""Stateless MCP tool serving; network framing belongs to ServerTransport."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import inspect
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Awaitable, Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any, Protocol, TypeAlias, TypedDict
|
|
12
|
+
|
|
13
|
+
from prism_mcp import (
|
|
14
|
+
KNOWN_PROTOCOL_VERSIONS,
|
|
15
|
+
LATEST_PROTOCOL_VERSION,
|
|
16
|
+
ErrorCode,
|
|
17
|
+
McpError,
|
|
18
|
+
MirroredParameters,
|
|
19
|
+
ResultGuard,
|
|
20
|
+
ToolDefinition,
|
|
21
|
+
ToolGate,
|
|
22
|
+
ToolResult,
|
|
23
|
+
TransportRequest,
|
|
24
|
+
TrustPolicy,
|
|
25
|
+
allow_all,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
from .http import LoopbackHttpTransport
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"SUPPORTED_PROTOCOL_VERSIONS",
|
|
32
|
+
"ErrorCode",
|
|
33
|
+
"InMemoryTransport",
|
|
34
|
+
"JsonObject",
|
|
35
|
+
"LoopbackHttpTransport",
|
|
36
|
+
"McpError",
|
|
37
|
+
"MirroredParameters",
|
|
38
|
+
"ResultGuard",
|
|
39
|
+
"Server",
|
|
40
|
+
"ServerTransport",
|
|
41
|
+
"ToolContext",
|
|
42
|
+
"ToolDefinition",
|
|
43
|
+
"ToolGate",
|
|
44
|
+
"ToolHandler",
|
|
45
|
+
"ToolResult",
|
|
46
|
+
"TransportRequest",
|
|
47
|
+
"TrustPolicy",
|
|
48
|
+
"allow_all",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
# TrustPolicy is a CLIENT defence against a hostile server's definitions, not an
|
|
52
|
+
# inbound authorization policy. The embedder owns registration; ToolGate admits calls.
|
|
53
|
+
JsonObject: TypeAlias = dict[str, Any]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ToolContext(TypedDict):
|
|
57
|
+
server: str
|
|
58
|
+
tool: str
|
|
59
|
+
headers: dict[str, str]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
ToolHandler: TypeAlias = Callable[[JsonObject, ToolContext], ToolResult | Awaitable[ToolResult]]
|
|
63
|
+
RequestHandler: TypeAlias = Callable[[TransportRequest], Awaitable[Any]]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Endpoint(TypedDict):
|
|
67
|
+
url: str
|
|
68
|
+
token: str | None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ServerTransport(Protocol):
|
|
72
|
+
async def listen(self, handler: RequestHandler) -> Endpoint: ...
|
|
73
|
+
|
|
74
|
+
async def close(self) -> None: ...
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
_VERSION = "io.modelcontextprotocol/protocolVersion"
|
|
78
|
+
_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities"
|
|
79
|
+
_CLIENT_INFO = "io.modelcontextprotocol/clientInfo"
|
|
80
|
+
_SERVER_INFO = "io.modelcontextprotocol/serverInfo"
|
|
81
|
+
_PREFIX = "mcp-param-"
|
|
82
|
+
_STATELESS_KEYS = (_VERSION, _CAPABILITIES, _CLIENT_INFO)
|
|
83
|
+
_SERVER_NAME = "prism-ai-mcp-server"
|
|
84
|
+
_SERVER_VERSION = "0.2.0"
|
|
85
|
+
|
|
86
|
+
# The handshake revisions, served for clients that open with `initialize`
|
|
87
|
+
# (Codex's MCP client always does). Newest first; an unknown requested revision
|
|
88
|
+
# is answered with the first, as the spec says.
|
|
89
|
+
_CLASSIC_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
|
|
90
|
+
|
|
91
|
+
#: Every MCP protocol version this server serves, newest first: the stateless
|
|
92
|
+
#: revision, then the handshake revisions. The standing rule is that the five
|
|
93
|
+
#: newest official versions are always here; protocol-versions.json publishes
|
|
94
|
+
#: this list for the drift watcher, and a test keeps the two identical.
|
|
95
|
+
SUPPORTED_PROTOCOL_VERSIONS: tuple[str, ...] = (LATEST_PROTOCOL_VERSION, *_CLASSIC_VERSIONS)
|
|
96
|
+
|
|
97
|
+
# Instructions are guidance for a model, not a document: bounded so one option
|
|
98
|
+
# cannot become a token sink.
|
|
99
|
+
_MAX_INSTRUCTIONS_BYTES = 16_384
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass(frozen=True)
|
|
103
|
+
class _RegisteredTool:
|
|
104
|
+
definition: ToolDefinition
|
|
105
|
+
handler: ToolHandler
|
|
106
|
+
mirrored: MirroredParameters
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class Server:
|
|
110
|
+
def __init__(
|
|
111
|
+
self,
|
|
112
|
+
server: str,
|
|
113
|
+
transport: ServerTransport,
|
|
114
|
+
gate: ToolGate | Callable[[str, str, JsonObject], Awaitable[bool]] | None = None,
|
|
115
|
+
guard: ResultGuard | None = None,
|
|
116
|
+
instructions: str | None = None,
|
|
117
|
+
) -> None:
|
|
118
|
+
# Guidance a client may give its model (G-277), sent in the initialize and
|
|
119
|
+
# server/discover results. It reaches the model, so it comes from the
|
|
120
|
+
# embedder's configuration and is fixed here; no request can set it.
|
|
121
|
+
self._instructions = _instructions_of(instructions)
|
|
122
|
+
self._server = server
|
|
123
|
+
self._transport = transport
|
|
124
|
+
self._gate = gate if gate is not None else allow_all
|
|
125
|
+
# Keep the serving limit independent of client defaults; clients frame provenance.
|
|
126
|
+
self._guard = (
|
|
127
|
+
guard if guard is not None else ResultGuard(max_bytes=65536, frame_provenance=False)
|
|
128
|
+
)
|
|
129
|
+
self._tools: dict[str, _RegisteredTool] = {}
|
|
130
|
+
self._refused: set[str] = set()
|
|
131
|
+
self._closed = False
|
|
132
|
+
|
|
133
|
+
def register(self, definition: ToolDefinition, handler: ToolHandler) -> None:
|
|
134
|
+
self._assert_open()
|
|
135
|
+
if definition.name in self._tools or definition.name in self._refused:
|
|
136
|
+
raise McpError(
|
|
137
|
+
ErrorCode.PROTOCOL_FAILURE, "A tool with this name is registered or refused."
|
|
138
|
+
)
|
|
139
|
+
snapshot = ToolDefinition.from_payload(_payload_of(definition))
|
|
140
|
+
try:
|
|
141
|
+
mirrored = MirroredParameters.from_schema(snapshot.name, snapshot.input_schema)
|
|
142
|
+
except McpError as error:
|
|
143
|
+
if error.code == ErrorCode.MIRRORED_PARAMETER_REFUSED.value:
|
|
144
|
+
self._refused.add(snapshot.name)
|
|
145
|
+
raise
|
|
146
|
+
self._tools[snapshot.name] = _RegisteredTool(snapshot, handler, mirrored)
|
|
147
|
+
|
|
148
|
+
async def listen(self) -> Endpoint:
|
|
149
|
+
self._assert_open()
|
|
150
|
+
return await self._transport.listen(self.handle)
|
|
151
|
+
|
|
152
|
+
async def close(self) -> None:
|
|
153
|
+
self._closed = True
|
|
154
|
+
await self._transport.close()
|
|
155
|
+
|
|
156
|
+
async def handle(self, request: TransportRequest) -> Any:
|
|
157
|
+
self._assert_open()
|
|
158
|
+
# Discovery precedes version selection, so no agreed-revision metadata
|
|
159
|
+
# can be required here. HTTP bearer/Origin checks stay in the transport.
|
|
160
|
+
if request.method == "server/discover":
|
|
161
|
+
discovered: JsonObject = {
|
|
162
|
+
"supportedVersions": [LATEST_PROTOCOL_VERSION],
|
|
163
|
+
"capabilities": {"tools": {}},
|
|
164
|
+
}
|
|
165
|
+
if self._instructions is not None:
|
|
166
|
+
discovered["instructions"] = self._instructions
|
|
167
|
+
return _complete({**discovered, "ttlMs": 0, "cacheScope": "private"})
|
|
168
|
+
params = request.params if request.params is not None else {}
|
|
169
|
+
# A request carrying ANY stateless metadata key is a stateless request and
|
|
170
|
+
# is held to the stateless rules; only one with none of them is classic. A
|
|
171
|
+
# half-formed stateless request must not fall through to the classic path.
|
|
172
|
+
meta = params.get("_meta") if isinstance(params, dict) else None
|
|
173
|
+
if not (isinstance(meta, dict) and any(key in meta for key in _STATELESS_KEYS)):
|
|
174
|
+
return await self._classic(request, params)
|
|
175
|
+
_assert_protocol(params)
|
|
176
|
+
if request.method == "tools/list":
|
|
177
|
+
return _complete({"tools": self._listed(), "ttlMs": 0, "cacheScope": "private"})
|
|
178
|
+
if request.method != "tools/call":
|
|
179
|
+
raise McpError(
|
|
180
|
+
ErrorCode.PROTOCOL_FAILURE,
|
|
181
|
+
"Only server/discover, tools/list and tools/call are supported on the stateless revision.",
|
|
182
|
+
)
|
|
183
|
+
return _complete(await self._call(request, params))
|
|
184
|
+
|
|
185
|
+
async def _classic(self, request: TransportRequest, params: JsonObject) -> Any:
|
|
186
|
+
"""The handshake protocol, for clients that open with ``initialize`` (Codex's always does).
|
|
187
|
+
|
|
188
|
+
Stateless per request, which the streamable-HTTP transport permits: no session id is issued, so
|
|
189
|
+
nothing is bound to one. Authentication is the transport's; the registry, gate, mirrors and result
|
|
190
|
+
guard are the stateless path's own.
|
|
191
|
+
"""
|
|
192
|
+
if request.method.startswith("notifications/"):
|
|
193
|
+
return None
|
|
194
|
+
if request.method == "initialize":
|
|
195
|
+
return _initialize(params, self._instructions)
|
|
196
|
+
header = request.headers.get("mcp-protocol-version")
|
|
197
|
+
if header is not None and header not in _CLASSIC_VERSIONS:
|
|
198
|
+
raise McpError(
|
|
199
|
+
ErrorCode.UNSUPPORTED_PROTOCOL_VERSION,
|
|
200
|
+
f"Protocol version [{header}] is not served on the handshake path; "
|
|
201
|
+
f"expected one of [{', '.join(_CLASSIC_VERSIONS)}].",
|
|
202
|
+
)
|
|
203
|
+
if request.method == "ping":
|
|
204
|
+
return {}
|
|
205
|
+
if request.method == "tools/list":
|
|
206
|
+
return {"tools": self._listed()}
|
|
207
|
+
if request.method == "tools/call":
|
|
208
|
+
return await self._call(request, params)
|
|
209
|
+
raise McpError(
|
|
210
|
+
ErrorCode.PROTOCOL_FAILURE,
|
|
211
|
+
"Only initialize, ping, tools/list and tools/call are supported.",
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def _listed(self) -> list[JsonObject]:
|
|
215
|
+
return [_without_nulls(_payload_of(tool.definition)) for tool in self._tools.values()]
|
|
216
|
+
|
|
217
|
+
async def _call(self, request: TransportRequest, params: JsonObject) -> JsonObject:
|
|
218
|
+
name = params.get("name")
|
|
219
|
+
if not isinstance(name, str) or not name:
|
|
220
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "tools/call requires a tool name.")
|
|
221
|
+
if name in self._refused:
|
|
222
|
+
raise McpError(
|
|
223
|
+
ErrorCode.MIRRORED_PARAMETER_REFUSED,
|
|
224
|
+
"The tool has invalid mirrored-parameter annotations.",
|
|
225
|
+
)
|
|
226
|
+
tool = self._tools.get(name)
|
|
227
|
+
if tool is None:
|
|
228
|
+
raise McpError(ErrorCode.TOOL_CALL_FAILED, "The requested tool is not registered.")
|
|
229
|
+
arguments = params.get("arguments", {})
|
|
230
|
+
if not isinstance(arguments, dict):
|
|
231
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Tool arguments must be an object.")
|
|
232
|
+
args = _clone_object(arguments)
|
|
233
|
+
headers = _mirrored_headers(request.headers)
|
|
234
|
+
_resolve_mirrors(tool.mirrored, headers, args)
|
|
235
|
+
verdict = self._gate(self._server, name, args)
|
|
236
|
+
# Serving is asynchronous in both languages; gates may be sync or async,
|
|
237
|
+
# as they may in the sibling client since prism-ai-mcp 0.2.1.
|
|
238
|
+
if inspect.isawaitable(verdict):
|
|
239
|
+
verdict = await verdict
|
|
240
|
+
# A gate that delegates and forgets an inner await resolves to another
|
|
241
|
+
# awaitable, which is truthy. Refused rather than read as consent (G-83).
|
|
242
|
+
if inspect.isawaitable(verdict):
|
|
243
|
+
if inspect.iscoroutine(verdict):
|
|
244
|
+
verdict.close()
|
|
245
|
+
raise TypeError(
|
|
246
|
+
f"The gate must resolve to a verdict, got {type(verdict).__name__}. "
|
|
247
|
+
"Await any coroutine inside the gate before returning."
|
|
248
|
+
)
|
|
249
|
+
if not verdict:
|
|
250
|
+
raise McpError(ErrorCode.TOOL_DENIED, "The gate refused this tool call.")
|
|
251
|
+
self._assert_open()
|
|
252
|
+
try:
|
|
253
|
+
result = tool.handler(args, {"server": self._server, "tool": name, "headers": headers})
|
|
254
|
+
if inspect.isawaitable(result):
|
|
255
|
+
result = await result
|
|
256
|
+
except Exception as error: # noqa: BLE001 -- sanitize arbitrary application failures
|
|
257
|
+
# Categories survive; arbitrary handler diagnostics may contain secrets.
|
|
258
|
+
code = error.code if isinstance(error, McpError) else ErrorCode.TOOL_CALL_FAILED.value
|
|
259
|
+
raise McpError(code, "The tool handler could not complete the request.") from None
|
|
260
|
+
if (
|
|
261
|
+
not isinstance(result, ToolResult)
|
|
262
|
+
or not isinstance(result.text, str)
|
|
263
|
+
or type(result.is_error) is not bool
|
|
264
|
+
):
|
|
265
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "The handler must return ToolResult.")
|
|
266
|
+
text = self._guard.guard(self._server, name, result.text)
|
|
267
|
+
return {"content": [{"type": "text", "text": text}], "isError": result.is_error}
|
|
268
|
+
|
|
269
|
+
def _assert_open(self) -> None:
|
|
270
|
+
if self._closed:
|
|
271
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "The server is closed.")
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _assert_protocol(params: JsonObject) -> None:
|
|
275
|
+
if not isinstance(params, dict) or not isinstance(params.get("_meta"), dict):
|
|
276
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Stateless requests require per-request _meta.")
|
|
277
|
+
meta = params["_meta"]
|
|
278
|
+
version = meta.get(_VERSION)
|
|
279
|
+
if version != LATEST_PROTOCOL_VERSION:
|
|
280
|
+
kind = "revision" if version in KNOWN_PROTOCOL_VERSIONS else "version"
|
|
281
|
+
value = version if isinstance(version, str) else "missing"
|
|
282
|
+
raise McpError(
|
|
283
|
+
ErrorCode.UNSUPPORTED_PROTOCOL_VERSION,
|
|
284
|
+
f"Protocol {kind} [{value}] is unsupported; expected [{LATEST_PROTOCOL_VERSION}].",
|
|
285
|
+
)
|
|
286
|
+
if not isinstance(meta.get(_CAPABILITIES), dict):
|
|
287
|
+
raise McpError(
|
|
288
|
+
ErrorCode.PROTOCOL_FAILURE,
|
|
289
|
+
"Requests require client capabilities in _meta.",
|
|
290
|
+
)
|
|
291
|
+
if _CLIENT_INFO in meta and not isinstance(meta[_CLIENT_INFO], dict):
|
|
292
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Client info must be an object when supplied.")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _instructions_of(value: object) -> str | None:
|
|
296
|
+
if value is None:
|
|
297
|
+
return None
|
|
298
|
+
if (
|
|
299
|
+
not isinstance(value, str)
|
|
300
|
+
or not value.strip()
|
|
301
|
+
or len(value.encode("utf-8")) > _MAX_INSTRUCTIONS_BYTES
|
|
302
|
+
):
|
|
303
|
+
raise McpError(
|
|
304
|
+
ErrorCode.PROTOCOL_FAILURE,
|
|
305
|
+
f"Server instructions must be a non-empty string of at most {_MAX_INSTRUCTIONS_BYTES} bytes.",
|
|
306
|
+
)
|
|
307
|
+
return value
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _initialize(params: JsonObject, instructions: str | None) -> JsonObject:
|
|
311
|
+
if (
|
|
312
|
+
not isinstance(params, dict)
|
|
313
|
+
or not isinstance(params.get("protocolVersion"), str)
|
|
314
|
+
or ("capabilities" in params and not isinstance(params["capabilities"], dict))
|
|
315
|
+
or ("clientInfo" in params and not isinstance(params["clientInfo"], dict))
|
|
316
|
+
):
|
|
317
|
+
raise McpError(
|
|
318
|
+
ErrorCode.PROTOCOL_FAILURE,
|
|
319
|
+
"initialize requires a protocolVersion, and object capabilities and clientInfo.",
|
|
320
|
+
)
|
|
321
|
+
requested = params["protocolVersion"]
|
|
322
|
+
version = requested if requested in _CLASSIC_VERSIONS else _CLASSIC_VERSIONS[0]
|
|
323
|
+
result: JsonObject = {
|
|
324
|
+
"protocolVersion": version,
|
|
325
|
+
"capabilities": {"tools": {}},
|
|
326
|
+
"serverInfo": {"name": _SERVER_NAME, "version": _SERVER_VERSION},
|
|
327
|
+
}
|
|
328
|
+
if instructions is not None:
|
|
329
|
+
result["instructions"] = instructions
|
|
330
|
+
return result
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _complete(result: JsonObject) -> JsonObject:
|
|
334
|
+
# Identify the serving software independently of the gate/context label.
|
|
335
|
+
# Fresh objects keep caller mutation from affecting subsequent responses.
|
|
336
|
+
return {
|
|
337
|
+
**result,
|
|
338
|
+
"resultType": "complete",
|
|
339
|
+
"_meta": {_SERVER_INFO: {"name": _SERVER_NAME, "version": _SERVER_VERSION}},
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _clone_object(value: JsonObject) -> JsonObject:
|
|
344
|
+
try:
|
|
345
|
+
result: JsonObject = json.loads(json.dumps(value, allow_nan=False))
|
|
346
|
+
return result
|
|
347
|
+
except (TypeError, ValueError, RecursionError):
|
|
348
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Expected JSON-serializable data.") from None
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _without_nulls(tool: JsonObject) -> JsonObject:
|
|
352
|
+
"""A tools/list entry with its null fields left out.
|
|
353
|
+
|
|
354
|
+
The spec types ``title`` (like every optional field) as an optional string: absent is valid, null is not.
|
|
355
|
+
Claude Code validates strictly and dropped the WHOLE server on one ``title: null`` (tynn, Genie 2,
|
|
356
|
+
2026-10-22). Pins are unaffected: ToolDefinition.from_payload() reads an absent title as None, so the
|
|
357
|
+
digest a client computes from the entry is the registered definition's.
|
|
358
|
+
"""
|
|
359
|
+
return {key: value for key, value in tool.items() if value is not None}
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _payload_of(tool: ToolDefinition) -> JsonObject:
|
|
363
|
+
return _clone_object(
|
|
364
|
+
{
|
|
365
|
+
"name": tool.name,
|
|
366
|
+
"description": tool.description,
|
|
367
|
+
"inputSchema": tool.input_schema,
|
|
368
|
+
"title": tool.title,
|
|
369
|
+
"annotations": tool.annotations,
|
|
370
|
+
}
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _mirrored_headers(raw: dict[str, str]) -> dict[str, str]:
|
|
375
|
+
headers: dict[str, str] = {}
|
|
376
|
+
for name, value in raw.items():
|
|
377
|
+
if not name.lower().startswith(_PREFIX):
|
|
378
|
+
continue
|
|
379
|
+
key = name[len(_PREFIX) :].lower()
|
|
380
|
+
if not isinstance(value, str) or key in headers:
|
|
381
|
+
raise McpError(
|
|
382
|
+
ErrorCode.PROTOCOL_FAILURE, "Mirrored headers require unambiguous string values."
|
|
383
|
+
)
|
|
384
|
+
headers[key] = value
|
|
385
|
+
# Authorization, Cookie, Origin and all other unnamespaced headers stay private.
|
|
386
|
+
return headers
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _resolve_mirrors(
|
|
390
|
+
mirrored: MirroredParameters, headers: dict[str, str], args: JsonObject
|
|
391
|
+
) -> None:
|
|
392
|
+
for name, parameter in mirrored.parameters.items():
|
|
393
|
+
raw = headers.get(name.lower())
|
|
394
|
+
if raw is None:
|
|
395
|
+
continue
|
|
396
|
+
value: str | int | bool = raw
|
|
397
|
+
if parameter["type"] == "boolean":
|
|
398
|
+
if raw not in ("true", "false"):
|
|
399
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Invalid mirrored boolean.")
|
|
400
|
+
value = raw == "true"
|
|
401
|
+
elif parameter["type"] == "integer":
|
|
402
|
+
if re.fullmatch(r"-?(0|[1-9][0-9]*)", raw) is None:
|
|
403
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Invalid mirrored integer.")
|
|
404
|
+
value = int(raw)
|
|
405
|
+
if abs(value) > 2**53 - 1:
|
|
406
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Invalid mirrored integer.")
|
|
407
|
+
target = args
|
|
408
|
+
path = parameter["path"]
|
|
409
|
+
for segment in path[:-1]:
|
|
410
|
+
if segment not in target:
|
|
411
|
+
target[segment] = {}
|
|
412
|
+
nested = target[segment]
|
|
413
|
+
if not isinstance(nested, dict):
|
|
414
|
+
raise McpError(
|
|
415
|
+
ErrorCode.PROTOCOL_FAILURE, "Mirrored path conflicts with tool arguments."
|
|
416
|
+
)
|
|
417
|
+
target = nested
|
|
418
|
+
leaf = path[-1]
|
|
419
|
+
if leaf in target and (
|
|
420
|
+
target[leaf] != value
|
|
421
|
+
or (
|
|
422
|
+
(type(target[leaf]) is bool or type(value) is bool)
|
|
423
|
+
and type(target[leaf]) is not type(value)
|
|
424
|
+
)
|
|
425
|
+
):
|
|
426
|
+
raise McpError(
|
|
427
|
+
ErrorCode.PROTOCOL_FAILURE, "Mirrored header conflicts with tool arguments."
|
|
428
|
+
)
|
|
429
|
+
target[leaf] = value
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
class InMemoryTransport:
|
|
433
|
+
"""In-process transport. No sockets, HTTP authentication or request timeout."""
|
|
434
|
+
|
|
435
|
+
def __init__(self) -> None:
|
|
436
|
+
self._handler: RequestHandler | None = None
|
|
437
|
+
self._closed = False
|
|
438
|
+
self._pending: dict[asyncio.Future[Any], asyncio.Future[Any]] = {}
|
|
439
|
+
|
|
440
|
+
async def listen(self, handler: RequestHandler) -> Endpoint:
|
|
441
|
+
if self._closed or self._handler is not None:
|
|
442
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Transport is closed or already listening.")
|
|
443
|
+
self._handler = handler
|
|
444
|
+
return {"url": "memory://prism-mcp-server", "token": None}
|
|
445
|
+
|
|
446
|
+
async def request(self, request: TransportRequest) -> Any:
|
|
447
|
+
handler = self._handler
|
|
448
|
+
if self._closed or handler is None:
|
|
449
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Transport is not listening.")
|
|
450
|
+
task = asyncio.ensure_future(handler(request))
|
|
451
|
+
waiter: asyncio.Future[Any] = asyncio.get_running_loop().create_future()
|
|
452
|
+
self._pending[waiter] = task
|
|
453
|
+
|
|
454
|
+
def completed(future: asyncio.Future[Any]) -> None:
|
|
455
|
+
# Always consume completion, even if close already released the caller.
|
|
456
|
+
try:
|
|
457
|
+
result = future.result()
|
|
458
|
+
except asyncio.CancelledError:
|
|
459
|
+
if not waiter.done():
|
|
460
|
+
waiter.cancel()
|
|
461
|
+
except Exception as error: # noqa: BLE001 -- forward every handler task failure
|
|
462
|
+
if not waiter.done():
|
|
463
|
+
waiter.set_exception(error)
|
|
464
|
+
else:
|
|
465
|
+
if not waiter.done():
|
|
466
|
+
waiter.set_result(result)
|
|
467
|
+
|
|
468
|
+
task.add_done_callback(completed)
|
|
469
|
+
try:
|
|
470
|
+
return await waiter
|
|
471
|
+
finally:
|
|
472
|
+
self._pending.pop(waiter, None)
|
|
473
|
+
if not task.done():
|
|
474
|
+
task.cancel()
|
|
475
|
+
|
|
476
|
+
async def close(self) -> None:
|
|
477
|
+
self._closed = True
|
|
478
|
+
self._handler = None
|
|
479
|
+
for waiter, task in self._pending.items():
|
|
480
|
+
if not waiter.done():
|
|
481
|
+
waiter.set_exception(
|
|
482
|
+
McpError(ErrorCode.PROTOCOL_FAILURE, "Transport closed during request.")
|
|
483
|
+
)
|
|
484
|
+
task.cancel()
|
|
485
|
+
self._pending.clear()
|
|
486
|
+
# Do not wait on application code that may suppress cancellation. Pending
|
|
487
|
+
# request waiters must still be released; no network resource is held here.
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"""Authenticated loopback HTTP using only the Python standard library."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import concurrent.futures
|
|
7
|
+
import hashlib
|
|
8
|
+
import hmac
|
|
9
|
+
import json
|
|
10
|
+
import math
|
|
11
|
+
import re
|
|
12
|
+
import secrets
|
|
13
|
+
import socket
|
|
14
|
+
import threading
|
|
15
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
16
|
+
from typing import TYPE_CHECKING, Any
|
|
17
|
+
|
|
18
|
+
from prism_mcp import ErrorCode, McpError, TransportRequest
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from . import Endpoint, RequestHandler
|
|
22
|
+
|
|
23
|
+
_TOKEN = re.compile(r"[A-Za-z0-9._~+/-]+=*", re.ASCII)
|
|
24
|
+
_ORIGIN = re.compile(r"https?://(127\.0\.0\.1|\[::1\])(?::([1-9][0-9]{0,4}))?", re.ASCII)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _valid_origin(origin: str) -> bool:
|
|
28
|
+
match = _ORIGIN.fullmatch(origin)
|
|
29
|
+
return match is not None and (match[2] is None or int(match[2]) <= 65535)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class LoopbackHttpTransport:
|
|
33
|
+
"""POST-only JSON-RPC on literal 127.0.0.1. Handler work stays on the caller's loop."""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
*,
|
|
38
|
+
port: int = 0,
|
|
39
|
+
token: str | None = None,
|
|
40
|
+
allowed_origins: list[str] | tuple[str, ...] | None = None,
|
|
41
|
+
max_request_bytes: int = 1024 * 1024,
|
|
42
|
+
) -> None:
|
|
43
|
+
if type(port) is not int or not 0 <= port <= 65535:
|
|
44
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Invalid HTTP port.")
|
|
45
|
+
if type(max_request_bytes) is not int or max_request_bytes <= 0:
|
|
46
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Invalid HTTP request limit.")
|
|
47
|
+
self._port = port
|
|
48
|
+
self._configured_token = token
|
|
49
|
+
self._configured_origins = None if allowed_origins is None else tuple(allowed_origins)
|
|
50
|
+
self._max_request_bytes = max_request_bytes
|
|
51
|
+
self._origins: set[str] = set()
|
|
52
|
+
self._expected = b""
|
|
53
|
+
self._server: _HttpServer | None = None
|
|
54
|
+
self._thread: threading.Thread | None = None
|
|
55
|
+
self._loop: asyncio.AbstractEventLoop | None = None
|
|
56
|
+
self._handler: RequestHandler | None = None
|
|
57
|
+
self._closed = False
|
|
58
|
+
self._closing: asyncio.Task[None] | None = None
|
|
59
|
+
self._lock = threading.Lock()
|
|
60
|
+
self._sockets: set[socket.socket] = set()
|
|
61
|
+
self._pending: set[concurrent.futures.Future[Any]] = set()
|
|
62
|
+
|
|
63
|
+
async def listen(self, handler: RequestHandler) -> Endpoint:
|
|
64
|
+
if self._closed or self._server is not None:
|
|
65
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Transport is closed or already listening.")
|
|
66
|
+
token = self._configured_token
|
|
67
|
+
if token is None:
|
|
68
|
+
token = secrets.token_hex(32)
|
|
69
|
+
# Reject configured empty/whitespace tokens before creating a listener.
|
|
70
|
+
if not isinstance(token, str) or _TOKEN.fullmatch(token) is None:
|
|
71
|
+
raise McpError(
|
|
72
|
+
ErrorCode.PROTOCOL_FAILURE,
|
|
73
|
+
"Bearer token must be non-empty and use bearer-token characters.",
|
|
74
|
+
)
|
|
75
|
+
if self._configured_origins is not None and any(
|
|
76
|
+
not _valid_origin(origin) for origin in self._configured_origins
|
|
77
|
+
):
|
|
78
|
+
raise McpError(
|
|
79
|
+
ErrorCode.PROTOCOL_FAILURE,
|
|
80
|
+
"Allowed origins must be exact numeric loopback origins.",
|
|
81
|
+
)
|
|
82
|
+
self._expected = hashlib.sha256(token.encode("ascii")).digest()
|
|
83
|
+
self._loop = asyncio.get_running_loop()
|
|
84
|
+
self._handler = handler
|
|
85
|
+
try:
|
|
86
|
+
server = _HttpServer(("127.0.0.1", self._port), self)
|
|
87
|
+
except OSError:
|
|
88
|
+
self._handler = None
|
|
89
|
+
raise McpError(
|
|
90
|
+
ErrorCode.PROTOCOL_FAILURE, "Could not start loopback HTTP transport."
|
|
91
|
+
) from None
|
|
92
|
+
self._server = server
|
|
93
|
+
origin = f"http://127.0.0.1:{server.server_port}"
|
|
94
|
+
self._origins = set(
|
|
95
|
+
(origin,) if self._configured_origins is None else self._configured_origins
|
|
96
|
+
)
|
|
97
|
+
self._thread = threading.Thread(
|
|
98
|
+
target=server.serve_forever,
|
|
99
|
+
kwargs={"poll_interval": 0.05},
|
|
100
|
+
name="prism-mcp-http",
|
|
101
|
+
daemon=True,
|
|
102
|
+
)
|
|
103
|
+
self._thread.start()
|
|
104
|
+
return {"url": origin + "/mcp", "token": token}
|
|
105
|
+
|
|
106
|
+
async def _dispatch(self, request: TransportRequest) -> Any:
|
|
107
|
+
handler = self._handler
|
|
108
|
+
if self._closed or handler is None:
|
|
109
|
+
raise McpError(ErrorCode.PROTOCOL_FAILURE, "Transport closed during request.")
|
|
110
|
+
return await handler(request)
|
|
111
|
+
|
|
112
|
+
async def close(self) -> None:
|
|
113
|
+
self._closed = True
|
|
114
|
+
if self._closing is None:
|
|
115
|
+
self._closing = asyncio.create_task(self._close())
|
|
116
|
+
await asyncio.shield(self._closing)
|
|
117
|
+
|
|
118
|
+
async def _close(self) -> None:
|
|
119
|
+
self._handler = None
|
|
120
|
+
with self._lock:
|
|
121
|
+
pending = tuple(self._pending)
|
|
122
|
+
sockets = tuple(self._sockets)
|
|
123
|
+
for future in pending:
|
|
124
|
+
future.cancel()
|
|
125
|
+
for connection in sockets:
|
|
126
|
+
try:
|
|
127
|
+
connection.shutdown(socket.SHUT_RDWR)
|
|
128
|
+
except OSError:
|
|
129
|
+
pass # An already disconnected peer owns no live connection.
|
|
130
|
+
connection.close()
|
|
131
|
+
server = self._server
|
|
132
|
+
if server is not None:
|
|
133
|
+
await asyncio.to_thread(server.shutdown)
|
|
134
|
+
server.server_close()
|
|
135
|
+
if self._thread is not None:
|
|
136
|
+
await asyncio.to_thread(self._thread.join)
|
|
137
|
+
# Do not await handler-owned work that suppresses cancellation. Listener
|
|
138
|
+
# and request sockets are already released independently of that work.
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class _HttpServer(ThreadingHTTPServer):
|
|
142
|
+
daemon_threads = True
|
|
143
|
+
block_on_close = False
|
|
144
|
+
|
|
145
|
+
def __init__(self, address: tuple[str, int], owner: LoopbackHttpTransport) -> None:
|
|
146
|
+
self.owner = owner
|
|
147
|
+
super().__init__(address, _RequestHandler)
|
|
148
|
+
|
|
149
|
+
def get_request(self) -> tuple[socket.socket, Any]:
|
|
150
|
+
connection, address = super().get_request()
|
|
151
|
+
connection.settimeout(None)
|
|
152
|
+
with self.owner._lock:
|
|
153
|
+
if self.owner._closed:
|
|
154
|
+
connection.close()
|
|
155
|
+
raise OSError("Transport closed")
|
|
156
|
+
self.owner._sockets.add(connection)
|
|
157
|
+
return connection, address
|
|
158
|
+
|
|
159
|
+
def shutdown_request(self, request: Any) -> None:
|
|
160
|
+
try:
|
|
161
|
+
super().shutdown_request(request)
|
|
162
|
+
finally:
|
|
163
|
+
with self.owner._lock:
|
|
164
|
+
self.owner._sockets.discard(request)
|
|
165
|
+
|
|
166
|
+
def handle_error(self, request: Any, client_address: Any) -> None:
|
|
167
|
+
# stdlib's default traceback may include embedder diagnostics. Never log.
|
|
168
|
+
return
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class _RequestHandler(BaseHTTPRequestHandler):
|
|
172
|
+
server: _HttpServer
|
|
173
|
+
protocol_version = "HTTP/1.1"
|
|
174
|
+
|
|
175
|
+
def log_message(self, format: str, *args: Any) -> None:
|
|
176
|
+
return # No access log: requests and credentials stay private.
|
|
177
|
+
|
|
178
|
+
def _authorize(self) -> int | None:
|
|
179
|
+
owner = self.server.owner
|
|
180
|
+
origins = self.headers.get_all("Origin")
|
|
181
|
+
if origins is not None and (len(origins) != 1 or origins[0] not in owner._origins):
|
|
182
|
+
return 403
|
|
183
|
+
values = self.headers.get_all("Authorization")
|
|
184
|
+
match = (
|
|
185
|
+
re.fullmatch(r"Bearer ([A-Za-z0-9._~+/-]+=*)", values[0], re.IGNORECASE | re.ASCII)
|
|
186
|
+
if values is not None and len(values) == 1
|
|
187
|
+
else None
|
|
188
|
+
)
|
|
189
|
+
if match is None or not hmac.compare_digest(
|
|
190
|
+
hashlib.sha256(match[1].encode("ascii")).digest(), owner._expected
|
|
191
|
+
):
|
|
192
|
+
return 401
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
def handle_expect_100(self) -> bool:
|
|
196
|
+
status = self._authorize()
|
|
197
|
+
if status is not None:
|
|
198
|
+
self._send(status, _rpc_error(None, -32000))
|
|
199
|
+
return False
|
|
200
|
+
return super().handle_expect_100()
|
|
201
|
+
|
|
202
|
+
def parse_request(self) -> bool:
|
|
203
|
+
if not super().parse_request():
|
|
204
|
+
return False
|
|
205
|
+
status = self._authorize()
|
|
206
|
+
if status is not None:
|
|
207
|
+
self._send(status, _rpc_error(None, -32000))
|
|
208
|
+
return False
|
|
209
|
+
return True
|
|
210
|
+
|
|
211
|
+
def do_GET(self) -> None:
|
|
212
|
+
self._send(405, _rpc_error(None, -32600))
|
|
213
|
+
|
|
214
|
+
do_HEAD = do_GET
|
|
215
|
+
do_OPTIONS = do_GET
|
|
216
|
+
do_PUT = do_GET
|
|
217
|
+
do_DELETE = do_GET
|
|
218
|
+
do_PATCH = do_GET
|
|
219
|
+
do_CONNECT = do_GET
|
|
220
|
+
|
|
221
|
+
def do_POST(self) -> None:
|
|
222
|
+
try:
|
|
223
|
+
self._post()
|
|
224
|
+
except (OSError, concurrent.futures.CancelledError):
|
|
225
|
+
return # Peer/transport closed. No response connection remains.
|
|
226
|
+
except Exception: # noqa: BLE001 -- transport diagnostics must not escape
|
|
227
|
+
self._send(500, _rpc_error(None, -32603))
|
|
228
|
+
|
|
229
|
+
def _post(self) -> None:
|
|
230
|
+
owner = self.server.owner
|
|
231
|
+
if self.path != "/mcp":
|
|
232
|
+
self._send(404, _rpc_error(None, -32600))
|
|
233
|
+
return
|
|
234
|
+
if self.headers.get("Upgrade") is not None:
|
|
235
|
+
self._send(405, _rpc_error(None, -32600))
|
|
236
|
+
return
|
|
237
|
+
accept = self.headers.get("Accept")
|
|
238
|
+
if accept and not any(
|
|
239
|
+
entry.split(";")[0].strip().lower() in ("application/json", "*/*")
|
|
240
|
+
for entry in accept.split(",")
|
|
241
|
+
):
|
|
242
|
+
self._send(406, _rpc_error(None, -32600))
|
|
243
|
+
return
|
|
244
|
+
if self.headers.get("Content-Type", "").split(";")[0].strip().lower() != "application/json":
|
|
245
|
+
self._send(415, _rpc_error(None, -32600))
|
|
246
|
+
return
|
|
247
|
+
headers: dict[str, str] = {}
|
|
248
|
+
for name, value in self.headers.items():
|
|
249
|
+
key = name.lower()
|
|
250
|
+
if key in headers:
|
|
251
|
+
self._send(400, _rpc_error(None, -32600))
|
|
252
|
+
return
|
|
253
|
+
headers[key] = value
|
|
254
|
+
if "transfer-encoding" in headers:
|
|
255
|
+
self._send(400, _rpc_error(None, -32600))
|
|
256
|
+
return
|
|
257
|
+
length = headers.get("content-length", "")
|
|
258
|
+
if re.fullmatch(r"0|[1-9][0-9]*", length, re.ASCII) is None:
|
|
259
|
+
self._send(411, _rpc_error(None, -32600))
|
|
260
|
+
return
|
|
261
|
+
if len(length) > 10 or int(length) > owner._max_request_bytes:
|
|
262
|
+
self._send(413, _rpc_error(None, -32600))
|
|
263
|
+
return
|
|
264
|
+
data = self.rfile.read(int(length))
|
|
265
|
+
if len(data) != int(length):
|
|
266
|
+
self._send(400, _rpc_error(None, -32600))
|
|
267
|
+
return
|
|
268
|
+
try:
|
|
269
|
+
body = json.loads(data.decode("utf-8"), parse_constant=_reject_constant)
|
|
270
|
+
except (UnicodeDecodeError, ValueError, RecursionError):
|
|
271
|
+
self._send(400, _rpc_error(None, -32700))
|
|
272
|
+
return
|
|
273
|
+
# A notification carries no id and gets no result; only `notifications/*`
|
|
274
|
+
# methods may omit it (the classic `notifications/initialized` does).
|
|
275
|
+
notification = (
|
|
276
|
+
isinstance(body, dict)
|
|
277
|
+
and "id" not in body
|
|
278
|
+
and isinstance(body.get("method"), str)
|
|
279
|
+
and body["method"].startswith("notifications/")
|
|
280
|
+
)
|
|
281
|
+
if (
|
|
282
|
+
not isinstance(body, dict)
|
|
283
|
+
or body.get("jsonrpc") != "2.0"
|
|
284
|
+
or not (
|
|
285
|
+
notification
|
|
286
|
+
or isinstance(body.get("id"), str)
|
|
287
|
+
or (type(body.get("id")) in (int, float) and math.isfinite(body["id"]))
|
|
288
|
+
)
|
|
289
|
+
or not isinstance(body.get("method"), str)
|
|
290
|
+
or ("params" in body and not isinstance(body["params"], dict))
|
|
291
|
+
):
|
|
292
|
+
self._send(400, _rpc_error(None, -32600))
|
|
293
|
+
return
|
|
294
|
+
loop = owner._loop
|
|
295
|
+
assert loop is not None
|
|
296
|
+
with owner._lock:
|
|
297
|
+
if owner._closed:
|
|
298
|
+
return
|
|
299
|
+
future = asyncio.run_coroutine_threadsafe(
|
|
300
|
+
owner._dispatch(TransportRequest(body["method"], body.get("params"), headers)), loop
|
|
301
|
+
)
|
|
302
|
+
owner._pending.add(future)
|
|
303
|
+
try:
|
|
304
|
+
if notification:
|
|
305
|
+
# Streamable HTTP answers an accepted notification 202 with no body.
|
|
306
|
+
try:
|
|
307
|
+
future.result()
|
|
308
|
+
except concurrent.futures.CancelledError:
|
|
309
|
+
return
|
|
310
|
+
except Exception: # noqa: BLE001 -- never return application diagnostics
|
|
311
|
+
if not owner._closed:
|
|
312
|
+
self._send(400, _rpc_error(None, -32600))
|
|
313
|
+
return
|
|
314
|
+
if not owner._closed:
|
|
315
|
+
self._send_accepted()
|
|
316
|
+
return
|
|
317
|
+
try:
|
|
318
|
+
result = future.result() # Deliberately no request deadline.
|
|
319
|
+
reply = {"jsonrpc": "2.0", "id": body["id"], "result": result}
|
|
320
|
+
except McpError as error:
|
|
321
|
+
reply = _rpc_error(body["id"], -32000, error.code)
|
|
322
|
+
except concurrent.futures.CancelledError:
|
|
323
|
+
return
|
|
324
|
+
except Exception: # noqa: BLE001 -- never return application diagnostics
|
|
325
|
+
reply = _rpc_error(body["id"], -32000, ErrorCode.PROTOCOL_FAILURE.value)
|
|
326
|
+
if not owner._closed:
|
|
327
|
+
self._send(200, reply)
|
|
328
|
+
finally:
|
|
329
|
+
with owner._lock:
|
|
330
|
+
owner._pending.discard(future)
|
|
331
|
+
|
|
332
|
+
def _send_accepted(self) -> None:
|
|
333
|
+
self.close_connection = True
|
|
334
|
+
self.send_response(202)
|
|
335
|
+
self.send_header("Content-Length", "0")
|
|
336
|
+
self.send_header("Connection", "close")
|
|
337
|
+
self.send_header("Cache-Control", "no-store")
|
|
338
|
+
self.end_headers()
|
|
339
|
+
|
|
340
|
+
def _send(self, status: int, body: Any) -> None:
|
|
341
|
+
data = json.dumps(body, ensure_ascii=True, allow_nan=False).encode("utf-8")
|
|
342
|
+
self.close_connection = True
|
|
343
|
+
self.send_response(status)
|
|
344
|
+
self.send_header("Content-Type", "application/json")
|
|
345
|
+
self.send_header("Content-Length", str(len(data)))
|
|
346
|
+
self.send_header("Connection", "close")
|
|
347
|
+
self.send_header("Cache-Control", "no-store")
|
|
348
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
349
|
+
self.end_headers()
|
|
350
|
+
self.wfile.write(data)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _reject_constant(value: str) -> Any:
|
|
354
|
+
raise ValueError("Non-JSON numeric constant")
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _rpc_error(identifier: Any, code: int, category: str | None = None) -> dict[str, Any]:
|
|
358
|
+
error: dict[str, Any] = {"code": code, "message": "MCP request refused."}
|
|
359
|
+
if category is not None:
|
|
360
|
+
error["data"] = {"code": category}
|
|
361
|
+
return {"jsonrpc": "2.0", "id": identifier, "error": error}
|
|
File without changes
|