agent-did-mcp 1.0.0rc5__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.
- agent_did_mcp-1.0.0rc5/PKG-INFO +124 -0
- agent_did_mcp-1.0.0rc5/README.md +107 -0
- agent_did_mcp-1.0.0rc5/pyproject.toml +51 -0
- agent_did_mcp-1.0.0rc5/setup.cfg +4 -0
- agent_did_mcp-1.0.0rc5/src/agent_did_mcp/__init__.py +31 -0
- agent_did_mcp-1.0.0rc5/src/agent_did_mcp/client.py +183 -0
- agent_did_mcp-1.0.0rc5/src/agent_did_mcp/metadata.py +59 -0
- agent_did_mcp-1.0.0rc5/src/agent_did_mcp/server.py +198 -0
- agent_did_mcp-1.0.0rc5/src/agent_did_mcp.egg-info/PKG-INFO +124 -0
- agent_did_mcp-1.0.0rc5/src/agent_did_mcp.egg-info/SOURCES.txt +13 -0
- agent_did_mcp-1.0.0rc5/src/agent_did_mcp.egg-info/dependency_links.txt +1 -0
- agent_did_mcp-1.0.0rc5/src/agent_did_mcp.egg-info/requires.txt +9 -0
- agent_did_mcp-1.0.0rc5/src/agent_did_mcp.egg-info/top_level.txt +1 -0
- agent_did_mcp-1.0.0rc5/tests/test_client_and_metadata.py +211 -0
- agent_did_mcp-1.0.0rc5/tests/test_end_to_end.py +113 -0
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agent-did-mcp
|
|
3
|
+
Version: 1.0.0rc5
|
|
4
|
+
Summary: Model Context Protocol (MCP) integration for Agent-DID: OAuth client assertions signed by the agent's DID key, HTTP Message Signatures on MCP requests and a verifying ASGI middleware.
|
|
5
|
+
Author-email: Edison Munoz <edison.munoz@agent-did.org>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: agent-did-sdk==1.0.0rc5
|
|
10
|
+
Requires-Dist: mcp<3,>=2.3
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
13
|
+
Requires-Dist: pytest<10.0,>=8.0; extra == "dev"
|
|
14
|
+
Requires-Dist: pytest-asyncio<2.0,>=0.23; extra == "dev"
|
|
15
|
+
Requires-Dist: ruff>=0.4; extra == "dev"
|
|
16
|
+
Requires-Dist: mypy>=1.10; extra == "dev"
|
|
17
|
+
|
|
18
|
+
# Agent-DID × Model Context Protocol (MCP) Integration
|
|
19
|
+
|
|
20
|
+
> **Design:** [ADR-008](../../docs/ADR-008-Delegation-OAuth-and-MCP.md) (D-12c, D-12d)
|
|
21
|
+
|
|
22
|
+
Agent-DID for MCP clients and servers that use the Streamable HTTP transport, built on the official [`mcp` Python SDK](https://pypi.org/project/mcp/) (2.x). An agent authenticates to an MCP authorization server with a JWT client assertion signed by its DID key, and can sign every MCP request so the server learns which agent DID sent it.
|
|
23
|
+
|
|
24
|
+
This package works alongside MCP authorization (OAuth 2.1), not instead of it. It is aligned with the MCP authorization specification and its OAuth Client Credentials extension; it is **not** verified against an MCP conformance suite.
|
|
25
|
+
|
|
26
|
+
## What it provides
|
|
27
|
+
|
|
28
|
+
| Piece | Side | What it does |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| `create_agent_did_oauth_provider(...)` | client | The `mcp` SDK's `PrivateKeyJWTOAuthProvider` (client credentials, `private_key_jwt`, RFC 7523) with a fresh DID client assertion per token request (`agent_did_sdk.create_client_assertion`) |
|
|
31
|
+
| `agent_did_assertion_provider(...)` | client | The `assertion_provider` callback alone, for your own provider setup |
|
|
32
|
+
| `AgentDidMcpAuth` | client | An `httpx2.Auth` that signs each request to the MCP server's origin with an Agent-DID HTTP Message Signature (RFC-001 §6.5), optionally with a capability (§6.7), after an `inner` auth (the OAuth provider) has added its token. Requests to other origins (the authorization server) are not signed |
|
|
33
|
+
| `AgentDidSignatureMiddleware` | server | An ASGI middleware for any app (for example `MCPServer.streamable_http_app()`): verifies the signature, or the capability invocation, of each request under `protected_paths` and answers `401` (`403` for `capability_required`, `413` for `body_too_large`) with the reason |
|
|
34
|
+
| `get_agent_did_principal(ctx)` | server | In a tool handler: the verified `AgentDidPrincipal` (`did`, `key_id`, `controllers`, `capability_id`, `allowed_action`…) |
|
|
35
|
+
| `client_metadata_routes(...)` | client's web host | Starlette routes that serve a Client ID Metadata Document (CIMD) and a JWKS built from the DID document |
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
Requires Python 3.11+ (the `mcp` 2.x SDK depends on `httpx2`, which needs 3.11).
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
cd sdk-python && python -m pip install -e ".[dev]"
|
|
43
|
+
cd ../integrations/mcp && python -m pip install -e ".[dev]"
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Server: verify the calling agent
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from mcp.server.mcpserver import Context, MCPServer
|
|
50
|
+
from agent_did_mcp import AgentDidSignatureMiddleware, get_agent_did_principal
|
|
51
|
+
|
|
52
|
+
server = MCPServer("files")
|
|
53
|
+
|
|
54
|
+
@server.tool()
|
|
55
|
+
def whoami(ctx: Context) -> str:
|
|
56
|
+
principal = get_agent_did_principal(ctx)
|
|
57
|
+
return principal.did if principal else "anonymous"
|
|
58
|
+
|
|
59
|
+
app = AgentDidSignatureMiddleware(
|
|
60
|
+
server.streamable_http_app(),
|
|
61
|
+
agent_identity=identity, # an AgentIdentity whose client resolves DIDs
|
|
62
|
+
public_base_url="https://mcp.example.com", # the origin clients sign for (behind a proxy)
|
|
63
|
+
allowed_dids=["did:webvh:…:agents:caller"], # or allowed_controllers=[...]
|
|
64
|
+
)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
A valid signature proves which DID sent the request, not what it may do: restrict senders with `allowed_dids` / `allowed_controllers`, or require a capability (`root_controllers={"https://mcp.example.com/mcp": [owner_did]}, require_capability=True`). The middleware reads at most `max_body_bytes` (1 MiB) of each body to check `Content-Digest`. Bearer tokens are still checked by the MCP server's own authorization.
|
|
68
|
+
|
|
69
|
+
## Client: OAuth token plus signed requests
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import httpx2
|
|
73
|
+
from mcp.client.session import ClientSession
|
|
74
|
+
from mcp.client.streamable_http import streamable_http_client
|
|
75
|
+
from agent_did_mcp import AgentDidMcpAuth, create_agent_did_oauth_provider
|
|
76
|
+
|
|
77
|
+
oauth = create_agent_did_oauth_provider(
|
|
78
|
+
server_url="https://mcp.example.com/mcp",
|
|
79
|
+
client_id="https://agent.example.com/oauth/client.json", # CIMD URL, or a pre-registered id
|
|
80
|
+
issuer="https://auth.example.com", # the authorization server's issuer
|
|
81
|
+
verification_method_id=f"{did}#key-1", # an `authentication` key
|
|
82
|
+
agent_private_key=private_key_hex, # or signer=<KMS / HSM AgentSigner>
|
|
83
|
+
storage=token_storage,
|
|
84
|
+
)
|
|
85
|
+
auth = AgentDidMcpAuth(
|
|
86
|
+
agent_identity=identity,
|
|
87
|
+
server_url="https://mcp.example.com/mcp",
|
|
88
|
+
agent_did=did,
|
|
89
|
+
verification_method_id=f"{did}#key-1", # an `assertionMethod` key
|
|
90
|
+
agent_private_key=private_key_hex,
|
|
91
|
+
inner=oauth,
|
|
92
|
+
)
|
|
93
|
+
async with httpx2.AsyncClient(auth=auth) as http_client:
|
|
94
|
+
async with streamable_http_client("https://mcp.example.com/mcp", http_client=http_client) as streams:
|
|
95
|
+
async with ClientSession(streams[0], streams[1]) as session:
|
|
96
|
+
await session.initialize()
|
|
97
|
+
await session.call_tool("whoami", {})
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The authorization server must know the client's keys. With CIMD it fetches the `client_id` URL: serve it with `client_metadata_routes(client_id=..., client_name=..., did_document=lambda: runtime.document, jwks_path="/oauth/jwks.json")`, and serve it again after a key rotation (authorization servers cache it). An authorization server that knows Agent-DID can instead check the assertion against the DID document with `AgentDidClient.verify_client_assertion`.
|
|
101
|
+
|
|
102
|
+
With a capability, pass `capability=` (a capability whose `controller` is the agent DID) and a `capabilityInvocation` key as `verification_method_id`.
|
|
103
|
+
|
|
104
|
+
## Example
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
python -m examples.mcp_signed_tool_call
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
A real `mcp` client calls a tool on a real `MCPServer` in process; the tool answers with the caller's verified DID.
|
|
111
|
+
|
|
112
|
+
## Limits
|
|
113
|
+
|
|
114
|
+
- Streamable HTTP only: stdio has no HTTP request to sign.
|
|
115
|
+
- Python only; a TypeScript MCP integration is planned after 1.0 (ADR-008).
|
|
116
|
+
- The middleware verifies requests; it does not sign responses.
|
|
117
|
+
- No claim of conformance with the MCP specification: the tests run the official `mcp` SDK client and server in process.
|
|
118
|
+
|
|
119
|
+
## Tests
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
python -m pytest tests -q # from integrations/mcp
|
|
123
|
+
npm run test:mcp # from the repository root
|
|
124
|
+
```
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# Agent-DID × Model Context Protocol (MCP) Integration
|
|
2
|
+
|
|
3
|
+
> **Design:** [ADR-008](../../docs/ADR-008-Delegation-OAuth-and-MCP.md) (D-12c, D-12d)
|
|
4
|
+
|
|
5
|
+
Agent-DID for MCP clients and servers that use the Streamable HTTP transport, built on the official [`mcp` Python SDK](https://pypi.org/project/mcp/) (2.x). An agent authenticates to an MCP authorization server with a JWT client assertion signed by its DID key, and can sign every MCP request so the server learns which agent DID sent it.
|
|
6
|
+
|
|
7
|
+
This package works alongside MCP authorization (OAuth 2.1), not instead of it. It is aligned with the MCP authorization specification and its OAuth Client Credentials extension; it is **not** verified against an MCP conformance suite.
|
|
8
|
+
|
|
9
|
+
## What it provides
|
|
10
|
+
|
|
11
|
+
| Piece | Side | What it does |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| `create_agent_did_oauth_provider(...)` | client | The `mcp` SDK's `PrivateKeyJWTOAuthProvider` (client credentials, `private_key_jwt`, RFC 7523) with a fresh DID client assertion per token request (`agent_did_sdk.create_client_assertion`) |
|
|
14
|
+
| `agent_did_assertion_provider(...)` | client | The `assertion_provider` callback alone, for your own provider setup |
|
|
15
|
+
| `AgentDidMcpAuth` | client | An `httpx2.Auth` that signs each request to the MCP server's origin with an Agent-DID HTTP Message Signature (RFC-001 §6.5), optionally with a capability (§6.7), after an `inner` auth (the OAuth provider) has added its token. Requests to other origins (the authorization server) are not signed |
|
|
16
|
+
| `AgentDidSignatureMiddleware` | server | An ASGI middleware for any app (for example `MCPServer.streamable_http_app()`): verifies the signature, or the capability invocation, of each request under `protected_paths` and answers `401` (`403` for `capability_required`, `413` for `body_too_large`) with the reason |
|
|
17
|
+
| `get_agent_did_principal(ctx)` | server | In a tool handler: the verified `AgentDidPrincipal` (`did`, `key_id`, `controllers`, `capability_id`, `allowed_action`…) |
|
|
18
|
+
| `client_metadata_routes(...)` | client's web host | Starlette routes that serve a Client ID Metadata Document (CIMD) and a JWKS built from the DID document |
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
Requires Python 3.11+ (the `mcp` 2.x SDK depends on `httpx2`, which needs 3.11).
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
cd sdk-python && python -m pip install -e ".[dev]"
|
|
26
|
+
cd ../integrations/mcp && python -m pip install -e ".[dev]"
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Server: verify the calling agent
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from mcp.server.mcpserver import Context, MCPServer
|
|
33
|
+
from agent_did_mcp import AgentDidSignatureMiddleware, get_agent_did_principal
|
|
34
|
+
|
|
35
|
+
server = MCPServer("files")
|
|
36
|
+
|
|
37
|
+
@server.tool()
|
|
38
|
+
def whoami(ctx: Context) -> str:
|
|
39
|
+
principal = get_agent_did_principal(ctx)
|
|
40
|
+
return principal.did if principal else "anonymous"
|
|
41
|
+
|
|
42
|
+
app = AgentDidSignatureMiddleware(
|
|
43
|
+
server.streamable_http_app(),
|
|
44
|
+
agent_identity=identity, # an AgentIdentity whose client resolves DIDs
|
|
45
|
+
public_base_url="https://mcp.example.com", # the origin clients sign for (behind a proxy)
|
|
46
|
+
allowed_dids=["did:webvh:…:agents:caller"], # or allowed_controllers=[...]
|
|
47
|
+
)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
A valid signature proves which DID sent the request, not what it may do: restrict senders with `allowed_dids` / `allowed_controllers`, or require a capability (`root_controllers={"https://mcp.example.com/mcp": [owner_did]}, require_capability=True`). The middleware reads at most `max_body_bytes` (1 MiB) of each body to check `Content-Digest`. Bearer tokens are still checked by the MCP server's own authorization.
|
|
51
|
+
|
|
52
|
+
## Client: OAuth token plus signed requests
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import httpx2
|
|
56
|
+
from mcp.client.session import ClientSession
|
|
57
|
+
from mcp.client.streamable_http import streamable_http_client
|
|
58
|
+
from agent_did_mcp import AgentDidMcpAuth, create_agent_did_oauth_provider
|
|
59
|
+
|
|
60
|
+
oauth = create_agent_did_oauth_provider(
|
|
61
|
+
server_url="https://mcp.example.com/mcp",
|
|
62
|
+
client_id="https://agent.example.com/oauth/client.json", # CIMD URL, or a pre-registered id
|
|
63
|
+
issuer="https://auth.example.com", # the authorization server's issuer
|
|
64
|
+
verification_method_id=f"{did}#key-1", # an `authentication` key
|
|
65
|
+
agent_private_key=private_key_hex, # or signer=<KMS / HSM AgentSigner>
|
|
66
|
+
storage=token_storage,
|
|
67
|
+
)
|
|
68
|
+
auth = AgentDidMcpAuth(
|
|
69
|
+
agent_identity=identity,
|
|
70
|
+
server_url="https://mcp.example.com/mcp",
|
|
71
|
+
agent_did=did,
|
|
72
|
+
verification_method_id=f"{did}#key-1", # an `assertionMethod` key
|
|
73
|
+
agent_private_key=private_key_hex,
|
|
74
|
+
inner=oauth,
|
|
75
|
+
)
|
|
76
|
+
async with httpx2.AsyncClient(auth=auth) as http_client:
|
|
77
|
+
async with streamable_http_client("https://mcp.example.com/mcp", http_client=http_client) as streams:
|
|
78
|
+
async with ClientSession(streams[0], streams[1]) as session:
|
|
79
|
+
await session.initialize()
|
|
80
|
+
await session.call_tool("whoami", {})
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The authorization server must know the client's keys. With CIMD it fetches the `client_id` URL: serve it with `client_metadata_routes(client_id=..., client_name=..., did_document=lambda: runtime.document, jwks_path="/oauth/jwks.json")`, and serve it again after a key rotation (authorization servers cache it). An authorization server that knows Agent-DID can instead check the assertion against the DID document with `AgentDidClient.verify_client_assertion`.
|
|
84
|
+
|
|
85
|
+
With a capability, pass `capability=` (a capability whose `controller` is the agent DID) and a `capabilityInvocation` key as `verification_method_id`.
|
|
86
|
+
|
|
87
|
+
## Example
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
python -m examples.mcp_signed_tool_call
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
A real `mcp` client calls a tool on a real `MCPServer` in process; the tool answers with the caller's verified DID.
|
|
94
|
+
|
|
95
|
+
## Limits
|
|
96
|
+
|
|
97
|
+
- Streamable HTTP only: stdio has no HTTP request to sign.
|
|
98
|
+
- Python only; a TypeScript MCP integration is planned after 1.0 (ADR-008).
|
|
99
|
+
- The middleware verifies requests; it does not sign responses.
|
|
100
|
+
- No claim of conformance with the MCP specification: the tests run the official `mcp` SDK client and server in process.
|
|
101
|
+
|
|
102
|
+
## Tests
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
python -m pytest tests -q # from integrations/mcp
|
|
106
|
+
npm run test:mcp # from the repository root
|
|
107
|
+
```
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "agent-did-mcp"
|
|
7
|
+
version = "1.0.0rc5"
|
|
8
|
+
description = "Model Context Protocol (MCP) integration for Agent-DID: OAuth client assertions signed by the agent's DID key, HTTP Message Signatures on MCP requests and a verifying ASGI middleware."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
# mcp 2.x depends on httpx2, which requires Python 3.11
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
license = "Apache-2.0"
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Edison Munoz", email = "edison.munoz@agent-did.org" }
|
|
15
|
+
]
|
|
16
|
+
dependencies = [
|
|
17
|
+
"agent-did-sdk==1.0.0rc5",
|
|
18
|
+
"mcp>=2.3,<3",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
dev = [
|
|
23
|
+
"build>=1.2",
|
|
24
|
+
"pytest>=8.0,<10.0",
|
|
25
|
+
"pytest-asyncio>=0.23,<2.0",
|
|
26
|
+
"ruff>=0.4",
|
|
27
|
+
"mypy>=1.10",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[tool.setuptools.packages.find]
|
|
31
|
+
where = ["src"]
|
|
32
|
+
|
|
33
|
+
[tool.pytest.ini_options]
|
|
34
|
+
testpaths = ["tests"]
|
|
35
|
+
asyncio_mode = "auto"
|
|
36
|
+
|
|
37
|
+
[tool.ruff]
|
|
38
|
+
target-version = "py311"
|
|
39
|
+
line-length = 120
|
|
40
|
+
|
|
41
|
+
[tool.ruff.lint]
|
|
42
|
+
select = ["E", "F", "I", "W", "UP"]
|
|
43
|
+
|
|
44
|
+
[tool.mypy]
|
|
45
|
+
strict = true
|
|
46
|
+
python_version = "3.11"
|
|
47
|
+
|
|
48
|
+
[tool.agent-did]
|
|
49
|
+
status = "functional"
|
|
50
|
+
roadmap = "ADR-008"
|
|
51
|
+
implementation = "functional"
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Public package surface for the Agent-DID MCP integration (ADR-008 D-12d)."""
|
|
2
|
+
|
|
3
|
+
from .client import (
|
|
4
|
+
AgentDidMcpAuth,
|
|
5
|
+
agent_did_assertion_provider,
|
|
6
|
+
create_agent_did_oauth_provider,
|
|
7
|
+
)
|
|
8
|
+
from .metadata import client_metadata_routes
|
|
9
|
+
from .server import (
|
|
10
|
+
DEFAULT_MAX_BODY_BYTES,
|
|
11
|
+
AgentDidPrincipal,
|
|
12
|
+
AgentDidSignatureMiddleware,
|
|
13
|
+
get_agent_did_principal,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
PACKAGE_STATUS = "functional"
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"PACKAGE_STATUS",
|
|
20
|
+
# Client
|
|
21
|
+
"AgentDidMcpAuth",
|
|
22
|
+
"agent_did_assertion_provider",
|
|
23
|
+
"create_agent_did_oauth_provider",
|
|
24
|
+
# Server
|
|
25
|
+
"DEFAULT_MAX_BODY_BYTES",
|
|
26
|
+
"AgentDidPrincipal",
|
|
27
|
+
"AgentDidSignatureMiddleware",
|
|
28
|
+
"get_agent_did_principal",
|
|
29
|
+
# Metadata
|
|
30
|
+
"client_metadata_routes",
|
|
31
|
+
]
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""MCP client side: OAuth client credentials with a DID client assertion, and Agent-DID request signatures.
|
|
2
|
+
|
|
3
|
+
Two independent pieces, usable together:
|
|
4
|
+
|
|
5
|
+
- :func:`agent_did_assertion_provider` returns the ``assertion_provider`` callback of the ``mcp`` SDK's
|
|
6
|
+
``PrivateKeyJWTOAuthProvider`` (OAuth Client Credentials extension, ``private_key_jwt``, RFC 7523): each call signs a
|
|
7
|
+
fresh client assertion with the agent's DID key for the authorization server's issuer
|
|
8
|
+
(``agent_did_sdk.create_client_assertion``). :func:`create_agent_did_oauth_provider` builds that provider.
|
|
9
|
+
- :class:`AgentDidMcpAuth` is an ``httpx2.Auth`` that signs every request to the MCP server's origin with an Agent-DID
|
|
10
|
+
HTTP Message Signature (RFC-001 §6.5), optionally with a capability (§6.7), after an inner auth (such as the OAuth
|
|
11
|
+
provider) has added its credentials. Requests to other origins (the authorization server) are passed on unsigned.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import AsyncGenerator, Awaitable, Callable, Generator
|
|
17
|
+
from typing import Any
|
|
18
|
+
from urllib.parse import urlsplit
|
|
19
|
+
|
|
20
|
+
import httpx2
|
|
21
|
+
from agent_did_sdk import (
|
|
22
|
+
AgentIdentity,
|
|
23
|
+
AgentSigner,
|
|
24
|
+
HttpTargetValidationOptions,
|
|
25
|
+
SignHttpRequestParams,
|
|
26
|
+
create_client_assertion,
|
|
27
|
+
)
|
|
28
|
+
from mcp.client.auth import TokenStorage
|
|
29
|
+
from mcp.client.auth.extensions.client_credentials import PrivateKeyJWTOAuthProvider
|
|
30
|
+
|
|
31
|
+
SIGNATURE_HEADERS = ("signature", "signature-input", "agent-did", "agent-did-capability", "content-digest", "date")
|
|
32
|
+
"""Header fields a signature sets; a re-signed request drops the previous values first."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _origin(url: str) -> tuple[str, str, int | None]:
|
|
36
|
+
parts = urlsplit(url)
|
|
37
|
+
scheme = parts.scheme.lower()
|
|
38
|
+
port = parts.port or {"https": 443, "http": 80}.get(scheme)
|
|
39
|
+
return scheme, (parts.hostname or "").lower(), port
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def agent_did_assertion_provider(
|
|
43
|
+
*,
|
|
44
|
+
client_id: str,
|
|
45
|
+
verification_method_id: str,
|
|
46
|
+
signer: AgentSigner | None = None,
|
|
47
|
+
agent_private_key: str | None = None,
|
|
48
|
+
lifetime_seconds: int = 60,
|
|
49
|
+
) -> Callable[[str], Awaitable[str]]:
|
|
50
|
+
"""The ``assertion_provider`` of ``PrivateKeyJWTOAuthProvider``: called with the authorization server's issuer
|
|
51
|
+
(the assertion ``aud``), it returns a client assertion (``iss`` = ``sub`` = *client_id*) signed by the
|
|
52
|
+
``authentication`` key *verification_method_id* of the agent DID, through *signer* or *agent_private_key*."""
|
|
53
|
+
if (signer is None) == (agent_private_key is None):
|
|
54
|
+
raise ValueError("Pass exactly one of signer or agent_private_key")
|
|
55
|
+
|
|
56
|
+
async def provider(audience: str) -> str:
|
|
57
|
+
return await create_client_assertion(
|
|
58
|
+
client_id=client_id,
|
|
59
|
+
issuer=audience,
|
|
60
|
+
verification_method_id=verification_method_id,
|
|
61
|
+
signer=signer,
|
|
62
|
+
agent_private_key=agent_private_key,
|
|
63
|
+
lifetime_seconds=lifetime_seconds,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
return provider
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def create_agent_did_oauth_provider(
|
|
70
|
+
*,
|
|
71
|
+
server_url: str,
|
|
72
|
+
client_id: str,
|
|
73
|
+
issuer: str,
|
|
74
|
+
verification_method_id: str,
|
|
75
|
+
storage: TokenStorage,
|
|
76
|
+
signer: AgentSigner | None = None,
|
|
77
|
+
agent_private_key: str | None = None,
|
|
78
|
+
scope: str | None = None,
|
|
79
|
+
) -> PrivateKeyJWTOAuthProvider:
|
|
80
|
+
"""The ``mcp`` SDK's OAuth client credentials provider (``private_key_jwt``) with DID client assertions.
|
|
81
|
+
|
|
82
|
+
*client_id* is the client's identifier at the authorization server *issuer* (a Client ID Metadata Document URL,
|
|
83
|
+
see :func:`agent_did_mcp.client_metadata_routes`, or a pre-registered id). The authorization server must know the
|
|
84
|
+
client's keys: from the metadata document's ``jwks`` / ``jwks_uri`` (``build_client_jwks``) or from the DID
|
|
85
|
+
document (``AgentDidClient.verify_client_assertion``)."""
|
|
86
|
+
return PrivateKeyJWTOAuthProvider(
|
|
87
|
+
server_url=server_url,
|
|
88
|
+
storage=storage,
|
|
89
|
+
client_id=client_id,
|
|
90
|
+
assertion_provider=agent_did_assertion_provider(
|
|
91
|
+
client_id=client_id,
|
|
92
|
+
verification_method_id=verification_method_id,
|
|
93
|
+
signer=signer,
|
|
94
|
+
agent_private_key=agent_private_key,
|
|
95
|
+
),
|
|
96
|
+
scope=scope,
|
|
97
|
+
issuer=issuer,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class AgentDidMcpAuth(httpx2.Auth):
|
|
102
|
+
"""Signs the requests to the MCP server's origin with an Agent-DID HTTP Message Signature.
|
|
103
|
+
|
|
104
|
+
*inner* (for example :func:`create_agent_did_oauth_provider`) runs first; each request it sends to the origin of
|
|
105
|
+
*server_url* (the MCP request itself, or its retry with a new token) is signed just before it goes out, so the
|
|
106
|
+
signature is fresh. With *capability* (a capability whose ``controller`` is *agent_did*), the signature covers it
|
|
107
|
+
(``Agent-DID-Capability``) and *verification_method_id* must be a ``capabilityInvocation`` key; otherwise it must be
|
|
108
|
+
an ``assertionMethod`` key. Async clients only (``httpx2.AsyncClient``).
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
requires_request_body = True
|
|
112
|
+
|
|
113
|
+
def __init__(
|
|
114
|
+
self,
|
|
115
|
+
*,
|
|
116
|
+
agent_identity: AgentIdentity,
|
|
117
|
+
server_url: str,
|
|
118
|
+
agent_did: str,
|
|
119
|
+
verification_method_id: str,
|
|
120
|
+
signer: AgentSigner | None = None,
|
|
121
|
+
agent_private_key: str | None = None,
|
|
122
|
+
capability: dict[str, Any] | None = None,
|
|
123
|
+
inner: httpx2.Auth | None = None,
|
|
124
|
+
http_security: HttpTargetValidationOptions | None = None,
|
|
125
|
+
) -> None:
|
|
126
|
+
if (signer is None) == (agent_private_key is None):
|
|
127
|
+
raise ValueError("Pass exactly one of signer or agent_private_key")
|
|
128
|
+
self._identity = agent_identity
|
|
129
|
+
self._origin = _origin(server_url)
|
|
130
|
+
self._agent_did = agent_did
|
|
131
|
+
self._key_id = verification_method_id
|
|
132
|
+
self._signer = signer
|
|
133
|
+
self._private_key = agent_private_key
|
|
134
|
+
self._capability = capability
|
|
135
|
+
self._inner = inner
|
|
136
|
+
self._http_security = http_security
|
|
137
|
+
|
|
138
|
+
def targets_server(self, request: httpx2.Request) -> bool:
|
|
139
|
+
"""Whether *request* goes to the MCP server's origin (and is signed)."""
|
|
140
|
+
return _origin(str(request.url)) == self._origin
|
|
141
|
+
|
|
142
|
+
async def sign(self, request: httpx2.Request) -> None:
|
|
143
|
+
"""Add (or replace) the Agent-DID signature headers of *request*."""
|
|
144
|
+
body = await request.aread()
|
|
145
|
+
headers = await self._identity.sign_http_request(
|
|
146
|
+
SignHttpRequestParams(
|
|
147
|
+
method=request.method,
|
|
148
|
+
url=str(request.url),
|
|
149
|
+
body=body or None,
|
|
150
|
+
agent_did=self._agent_did,
|
|
151
|
+
verification_method_id=self._key_id,
|
|
152
|
+
signer=self._signer,
|
|
153
|
+
agent_private_key=self._private_key,
|
|
154
|
+
capability=self._capability,
|
|
155
|
+
http_security=self._http_security,
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
for name in SIGNATURE_HEADERS:
|
|
159
|
+
if name in request.headers:
|
|
160
|
+
del request.headers[name]
|
|
161
|
+
request.headers.update(headers)
|
|
162
|
+
|
|
163
|
+
def sync_auth_flow(self, request: httpx2.Request) -> Generator[httpx2.Request, httpx2.Response, None]:
|
|
164
|
+
raise RuntimeError("AgentDidMcpAuth signs asynchronously: use httpx2.AsyncClient")
|
|
165
|
+
|
|
166
|
+
async def async_auth_flow(self, request: httpx2.Request) -> AsyncGenerator[httpx2.Request, httpx2.Response]:
|
|
167
|
+
if self._inner is None:
|
|
168
|
+
if self.targets_server(request):
|
|
169
|
+
await self.sign(request)
|
|
170
|
+
yield request
|
|
171
|
+
return
|
|
172
|
+
flow = self._inner.async_auth_flow(request)
|
|
173
|
+
try:
|
|
174
|
+
outgoing = await flow.__anext__()
|
|
175
|
+
while True:
|
|
176
|
+
if self.targets_server(outgoing):
|
|
177
|
+
await self.sign(outgoing)
|
|
178
|
+
response = yield outgoing
|
|
179
|
+
outgoing = await flow.asend(response)
|
|
180
|
+
except StopAsyncIteration:
|
|
181
|
+
return
|
|
182
|
+
finally:
|
|
183
|
+
await flow.aclose()
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Starlette routes that publish an agent's OAuth client metadata: a Client ID Metadata Document (CIMD) and a JWKS
|
|
2
|
+
built from its DID document (``agent_did_sdk.build_client_metadata_document`` / ``build_client_jwks``).
|
|
3
|
+
|
|
4
|
+
An MCP authorization server that supports CIMD fetches the document at the ``client_id`` URL and checks the client
|
|
5
|
+
assertions against its ``jwks``. The routes read the DID document on each request, so a key rotation shows up at once
|
|
6
|
+
(authorization servers cache the document: rotate with an overlap).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
|
|
15
|
+
from agent_did_sdk import AnyDidDocument, build_client_jwks, build_client_metadata_document
|
|
16
|
+
from starlette.requests import Request
|
|
17
|
+
from starlette.responses import JSONResponse
|
|
18
|
+
from starlette.routing import Route
|
|
19
|
+
|
|
20
|
+
DidDocumentSource = Callable[[], AnyDidDocument]
|
|
21
|
+
"""Returns the agent's current DID document (for example ``lambda: runtime_identity.document``)."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def client_metadata_routes(
|
|
25
|
+
*,
|
|
26
|
+
client_id: str,
|
|
27
|
+
client_name: str,
|
|
28
|
+
did_document: DidDocumentSource,
|
|
29
|
+
jwks_path: str | None = None,
|
|
30
|
+
client_uri: str | None = None,
|
|
31
|
+
max_age_seconds: int = 300,
|
|
32
|
+
) -> list[Route]:
|
|
33
|
+
"""Routes serving the CIMD at the path of *client_id* (an ``https`` URL on this app's origin) and, with
|
|
34
|
+
*jwks_path*, the JWKS there (the CIMD then names it in ``jwks_uri`` instead of embedding ``jwks``)."""
|
|
35
|
+
parts = urlsplit(client_id)
|
|
36
|
+
if parts.scheme != "https" or not parts.netloc or not parts.path or parts.query or parts.fragment:
|
|
37
|
+
raise ValueError("client_id must be an https URL with a path and no query or fragment")
|
|
38
|
+
jwks_uri = f"{parts.scheme}://{parts.netloc}{jwks_path}" if jwks_path else None
|
|
39
|
+
cache = {"cache-control": f"public, max-age={max_age_seconds}"}
|
|
40
|
+
|
|
41
|
+
def metadata() -> dict[str, Any]:
|
|
42
|
+
return build_client_metadata_document(
|
|
43
|
+
client_id=client_id,
|
|
44
|
+
client_name=client_name,
|
|
45
|
+
did_document=did_document(),
|
|
46
|
+
client_uri=client_uri,
|
|
47
|
+
jwks_uri=jwks_uri,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
async def serve_metadata(_request: Request) -> JSONResponse:
|
|
51
|
+
return JSONResponse(metadata(), headers=cache)
|
|
52
|
+
|
|
53
|
+
async def serve_jwks(_request: Request) -> JSONResponse:
|
|
54
|
+
return JSONResponse(build_client_jwks(did_document()), headers=cache)
|
|
55
|
+
|
|
56
|
+
routes = [Route(parts.path, serve_metadata, methods=["GET"])]
|
|
57
|
+
if jwks_path:
|
|
58
|
+
routes.append(Route(jwks_path, serve_jwks, methods=["GET"]))
|
|
59
|
+
return routes
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""MCP server side: an ASGI middleware that verifies Agent-DID request signatures and names the verified agent.
|
|
2
|
+
|
|
3
|
+
:class:`AgentDidSignatureMiddleware` wraps any ASGI app (for example ``MCPServer.streamable_http_app()``). For each
|
|
4
|
+
HTTP request under ``protected_paths`` it reads the body (up to ``max_body_bytes``), verifies the Agent-DID HTTP
|
|
5
|
+
Message Signature (RFC-001 §6.5) or, when the request carries ``Agent-DID-Capability``, the capability invocation
|
|
6
|
+
(§6.7), and either answers ``401`` with the rejection reason or passes the request on with the verified
|
|
7
|
+
:class:`AgentDidPrincipal` in ``scope["state"]["agent_did"]``. A tool handler reads it with
|
|
8
|
+
:func:`get_agent_did_principal` (``ctx.request_context.request.state``).
|
|
9
|
+
|
|
10
|
+
The signature is checked in addition to whatever authorization the MCP server applies (OAuth bearer tokens): it says
|
|
11
|
+
which agent DID sent the request, not what it may do. Authorization stays with the server (``allowed_dids``,
|
|
12
|
+
``allowed_controllers``, capabilities).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
from collections.abc import Sequence
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from agent_did_sdk import AgentIdentity, VerifyHttpRequestSignatureParams
|
|
23
|
+
from agent_did_sdk.core.types import VerifyHttpCapabilityInvocationParams
|
|
24
|
+
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
|
25
|
+
|
|
26
|
+
DEFAULT_MAX_BODY_BYTES = 1024 * 1024
|
|
27
|
+
"""Largest request body the middleware reads to check ``Content-Digest`` (1 MiB)."""
|
|
28
|
+
|
|
29
|
+
STATE_KEY = "agent_did"
|
|
30
|
+
"""Key of the verified :class:`AgentDidPrincipal` in ``scope["state"]``."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class AgentDidPrincipal:
|
|
35
|
+
"""The agent a verified request comes from."""
|
|
36
|
+
|
|
37
|
+
did: str
|
|
38
|
+
key_id: str | None
|
|
39
|
+
controllers: tuple[str, ...] = ()
|
|
40
|
+
capability_id: str | None = None
|
|
41
|
+
"""The invoked capability, when the request carried one."""
|
|
42
|
+
allowed_action: tuple[str, ...] | None = None
|
|
43
|
+
root_id: str | None = None
|
|
44
|
+
delegators: tuple[str, ...] = field(default_factory=tuple)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def get_agent_did_principal(source: Any) -> AgentDidPrincipal | None:
|
|
48
|
+
"""The verified principal of a request: *source* is an MCP tool ``Context``, a Starlette ``Request`` or an ASGI
|
|
49
|
+
scope. ``None`` when the request did not go through :class:`AgentDidSignatureMiddleware`."""
|
|
50
|
+
request_context = getattr(source, "request_context", None)
|
|
51
|
+
if request_context is not None:
|
|
52
|
+
source = getattr(request_context, "request", None)
|
|
53
|
+
if isinstance(source, dict):
|
|
54
|
+
state = source.get("state") or {}
|
|
55
|
+
principal = state.get(STATE_KEY)
|
|
56
|
+
else:
|
|
57
|
+
principal = getattr(getattr(source, "state", None), STATE_KEY, None)
|
|
58
|
+
return principal if isinstance(principal, AgentDidPrincipal) else None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class AgentDidSignatureMiddleware:
|
|
62
|
+
"""Verifies the Agent-DID signature of each HTTP request under *protected_paths* (path prefixes; default
|
|
63
|
+
``("/mcp",)``) and rejects the others with ``401``.
|
|
64
|
+
|
|
65
|
+
*public_base_url* (``https://mcp.example.com``) is the origin clients sign for, when the app runs behind a proxy;
|
|
66
|
+
otherwise the URL is rebuilt from the request (scheme, ``Host``, path, query). *root_controllers* enables
|
|
67
|
+
capability invocations (``Agent-DID-Capability``); *require_capability* refuses requests without one.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
def __init__(
|
|
71
|
+
self,
|
|
72
|
+
app: ASGIApp,
|
|
73
|
+
*,
|
|
74
|
+
agent_identity: AgentIdentity,
|
|
75
|
+
protected_paths: Sequence[str] = ("/mcp",),
|
|
76
|
+
public_base_url: str | None = None,
|
|
77
|
+
allowed_dids: list[str] | None = None,
|
|
78
|
+
allowed_controllers: list[str] | None = None,
|
|
79
|
+
root_controllers: dict[str, list[str]] | None = None,
|
|
80
|
+
require_capability: bool = False,
|
|
81
|
+
max_body_bytes: int = DEFAULT_MAX_BODY_BYTES,
|
|
82
|
+
) -> None:
|
|
83
|
+
if require_capability and not root_controllers:
|
|
84
|
+
raise ValueError("require_capability needs root_controllers")
|
|
85
|
+
self.app = app
|
|
86
|
+
self._identity = agent_identity
|
|
87
|
+
self._paths = tuple(protected_paths)
|
|
88
|
+
self._base = public_base_url.rstrip("/") if public_base_url else None
|
|
89
|
+
self._allowed_dids = allowed_dids
|
|
90
|
+
self._allowed_controllers = allowed_controllers
|
|
91
|
+
self._root_controllers = root_controllers
|
|
92
|
+
self._require_capability = require_capability
|
|
93
|
+
self._max_body = max_body_bytes
|
|
94
|
+
|
|
95
|
+
def _protected(self, path: str) -> bool:
|
|
96
|
+
return any(path == prefix or path.startswith(prefix.rstrip("/") + "/") for prefix in self._paths)
|
|
97
|
+
|
|
98
|
+
def _url(self, scope: Scope, headers: dict[str, str]) -> str:
|
|
99
|
+
path = scope.get("raw_path", b"").decode("latin-1").split("?", 1)[0] or scope["path"]
|
|
100
|
+
query = scope.get("query_string", b"").decode("latin-1")
|
|
101
|
+
if self._base is not None:
|
|
102
|
+
base = self._base
|
|
103
|
+
else:
|
|
104
|
+
host = headers.get("host")
|
|
105
|
+
if host is None:
|
|
106
|
+
server = scope.get("server") or ("localhost", None)
|
|
107
|
+
host = server[0] if server[1] is None else f"{server[0]}:{server[1]}"
|
|
108
|
+
base = f"{scope.get('scheme', 'http')}://{host}"
|
|
109
|
+
return f"{base}{path}?{query}" if query else f"{base}{path}"
|
|
110
|
+
|
|
111
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
112
|
+
if scope["type"] != "http" or not self._protected(scope["path"]):
|
|
113
|
+
await self.app(scope, receive, send)
|
|
114
|
+
return
|
|
115
|
+
body = bytearray()
|
|
116
|
+
more = True
|
|
117
|
+
while more:
|
|
118
|
+
message = await receive()
|
|
119
|
+
if message["type"] == "http.disconnect":
|
|
120
|
+
return
|
|
121
|
+
body.extend(message.get("body", b""))
|
|
122
|
+
more = message.get("more_body", False)
|
|
123
|
+
if len(body) > self._max_body:
|
|
124
|
+
await _reject(send, 413, "body_too_large")
|
|
125
|
+
return
|
|
126
|
+
headers = {key.decode("latin-1").lower(): value.decode("latin-1") for key, value in scope["headers"]}
|
|
127
|
+
principal, reason = await self._verify(scope["method"], self._url(scope, headers), headers, bytes(body))
|
|
128
|
+
if principal is None:
|
|
129
|
+
await _reject(send, 403 if reason == "capability_required" else 401, reason or "signature_invalid")
|
|
130
|
+
return
|
|
131
|
+
scope.setdefault("state", {})[STATE_KEY] = principal
|
|
132
|
+
replayed = False
|
|
133
|
+
|
|
134
|
+
async def replay() -> Message:
|
|
135
|
+
nonlocal replayed
|
|
136
|
+
if not replayed:
|
|
137
|
+
replayed = True
|
|
138
|
+
return {"type": "http.request", "body": bytes(body), "more_body": False}
|
|
139
|
+
return await receive()
|
|
140
|
+
|
|
141
|
+
await self.app(scope, replay, send)
|
|
142
|
+
|
|
143
|
+
async def _verify(
|
|
144
|
+
self, method: str, url: str, headers: dict[str, str], body: bytes
|
|
145
|
+
) -> tuple[AgentDidPrincipal | None, str | None]:
|
|
146
|
+
common: dict[str, Any] = {
|
|
147
|
+
"method": method,
|
|
148
|
+
"url": url,
|
|
149
|
+
"headers": headers,
|
|
150
|
+
"body": body or None,
|
|
151
|
+
"allowed_dids": self._allowed_dids,
|
|
152
|
+
"allowed_controllers": self._allowed_controllers,
|
|
153
|
+
}
|
|
154
|
+
client = self._identity.client
|
|
155
|
+
try:
|
|
156
|
+
if "agent-did-capability" in headers and self._root_controllers:
|
|
157
|
+
invocation = await client.verify_http_capability_invocation(
|
|
158
|
+
VerifyHttpCapabilityInvocationParams(**common, root_controllers=self._root_controllers)
|
|
159
|
+
)
|
|
160
|
+
if not invocation.ok or invocation.did is None:
|
|
161
|
+
return None, invocation.reason
|
|
162
|
+
return (
|
|
163
|
+
AgentDidPrincipal(
|
|
164
|
+
did=invocation.did,
|
|
165
|
+
key_id=invocation.key_id,
|
|
166
|
+
controllers=tuple(invocation.controllers),
|
|
167
|
+
capability_id=_capability_id(invocation.capability) or invocation.capability_id,
|
|
168
|
+
allowed_action=invocation.allowed_action,
|
|
169
|
+
root_id=invocation.root_id,
|
|
170
|
+
delegators=tuple(invocation.delegators),
|
|
171
|
+
),
|
|
172
|
+
None,
|
|
173
|
+
)
|
|
174
|
+
if self._require_capability:
|
|
175
|
+
return None, "capability_required"
|
|
176
|
+
result = await client.verify_http_request_signature_detailed(VerifyHttpRequestSignatureParams(**common))
|
|
177
|
+
except Exception:
|
|
178
|
+
return None, "malformed_headers"
|
|
179
|
+
if not result.ok or result.did is None:
|
|
180
|
+
return None, result.reason
|
|
181
|
+
return AgentDidPrincipal(did=result.did, key_id=result.key_id, controllers=tuple(result.controllers)), None
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _capability_id(capability: dict[str, Any] | None) -> str | None:
|
|
185
|
+
value = (capability or {}).get("id")
|
|
186
|
+
return value if isinstance(value, str) else None
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
async def _reject(send: Send, status: int, reason: str) -> None:
|
|
190
|
+
body = json.dumps({"error": "agent_did_signature_rejected", "reason": reason}).encode("utf-8")
|
|
191
|
+
await send(
|
|
192
|
+
{
|
|
193
|
+
"type": "http.response.start",
|
|
194
|
+
"status": status,
|
|
195
|
+
"headers": [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())],
|
|
196
|
+
}
|
|
197
|
+
)
|
|
198
|
+
await send({"type": "http.response.body", "body": body})
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agent-did-mcp
|
|
3
|
+
Version: 1.0.0rc5
|
|
4
|
+
Summary: Model Context Protocol (MCP) integration for Agent-DID: OAuth client assertions signed by the agent's DID key, HTTP Message Signatures on MCP requests and a verifying ASGI middleware.
|
|
5
|
+
Author-email: Edison Munoz <edison.munoz@agent-did.org>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: agent-did-sdk==1.0.0rc5
|
|
10
|
+
Requires-Dist: mcp<3,>=2.3
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
13
|
+
Requires-Dist: pytest<10.0,>=8.0; extra == "dev"
|
|
14
|
+
Requires-Dist: pytest-asyncio<2.0,>=0.23; extra == "dev"
|
|
15
|
+
Requires-Dist: ruff>=0.4; extra == "dev"
|
|
16
|
+
Requires-Dist: mypy>=1.10; extra == "dev"
|
|
17
|
+
|
|
18
|
+
# Agent-DID × Model Context Protocol (MCP) Integration
|
|
19
|
+
|
|
20
|
+
> **Design:** [ADR-008](../../docs/ADR-008-Delegation-OAuth-and-MCP.md) (D-12c, D-12d)
|
|
21
|
+
|
|
22
|
+
Agent-DID for MCP clients and servers that use the Streamable HTTP transport, built on the official [`mcp` Python SDK](https://pypi.org/project/mcp/) (2.x). An agent authenticates to an MCP authorization server with a JWT client assertion signed by its DID key, and can sign every MCP request so the server learns which agent DID sent it.
|
|
23
|
+
|
|
24
|
+
This package works alongside MCP authorization (OAuth 2.1), not instead of it. It is aligned with the MCP authorization specification and its OAuth Client Credentials extension; it is **not** verified against an MCP conformance suite.
|
|
25
|
+
|
|
26
|
+
## What it provides
|
|
27
|
+
|
|
28
|
+
| Piece | Side | What it does |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| `create_agent_did_oauth_provider(...)` | client | The `mcp` SDK's `PrivateKeyJWTOAuthProvider` (client credentials, `private_key_jwt`, RFC 7523) with a fresh DID client assertion per token request (`agent_did_sdk.create_client_assertion`) |
|
|
31
|
+
| `agent_did_assertion_provider(...)` | client | The `assertion_provider` callback alone, for your own provider setup |
|
|
32
|
+
| `AgentDidMcpAuth` | client | An `httpx2.Auth` that signs each request to the MCP server's origin with an Agent-DID HTTP Message Signature (RFC-001 §6.5), optionally with a capability (§6.7), after an `inner` auth (the OAuth provider) has added its token. Requests to other origins (the authorization server) are not signed |
|
|
33
|
+
| `AgentDidSignatureMiddleware` | server | An ASGI middleware for any app (for example `MCPServer.streamable_http_app()`): verifies the signature, or the capability invocation, of each request under `protected_paths` and answers `401` (`403` for `capability_required`, `413` for `body_too_large`) with the reason |
|
|
34
|
+
| `get_agent_did_principal(ctx)` | server | In a tool handler: the verified `AgentDidPrincipal` (`did`, `key_id`, `controllers`, `capability_id`, `allowed_action`…) |
|
|
35
|
+
| `client_metadata_routes(...)` | client's web host | Starlette routes that serve a Client ID Metadata Document (CIMD) and a JWKS built from the DID document |
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
Requires Python 3.11+ (the `mcp` 2.x SDK depends on `httpx2`, which needs 3.11).
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
cd sdk-python && python -m pip install -e ".[dev]"
|
|
43
|
+
cd ../integrations/mcp && python -m pip install -e ".[dev]"
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Server: verify the calling agent
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from mcp.server.mcpserver import Context, MCPServer
|
|
50
|
+
from agent_did_mcp import AgentDidSignatureMiddleware, get_agent_did_principal
|
|
51
|
+
|
|
52
|
+
server = MCPServer("files")
|
|
53
|
+
|
|
54
|
+
@server.tool()
|
|
55
|
+
def whoami(ctx: Context) -> str:
|
|
56
|
+
principal = get_agent_did_principal(ctx)
|
|
57
|
+
return principal.did if principal else "anonymous"
|
|
58
|
+
|
|
59
|
+
app = AgentDidSignatureMiddleware(
|
|
60
|
+
server.streamable_http_app(),
|
|
61
|
+
agent_identity=identity, # an AgentIdentity whose client resolves DIDs
|
|
62
|
+
public_base_url="https://mcp.example.com", # the origin clients sign for (behind a proxy)
|
|
63
|
+
allowed_dids=["did:webvh:…:agents:caller"], # or allowed_controllers=[...]
|
|
64
|
+
)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
A valid signature proves which DID sent the request, not what it may do: restrict senders with `allowed_dids` / `allowed_controllers`, or require a capability (`root_controllers={"https://mcp.example.com/mcp": [owner_did]}, require_capability=True`). The middleware reads at most `max_body_bytes` (1 MiB) of each body to check `Content-Digest`. Bearer tokens are still checked by the MCP server's own authorization.
|
|
68
|
+
|
|
69
|
+
## Client: OAuth token plus signed requests
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import httpx2
|
|
73
|
+
from mcp.client.session import ClientSession
|
|
74
|
+
from mcp.client.streamable_http import streamable_http_client
|
|
75
|
+
from agent_did_mcp import AgentDidMcpAuth, create_agent_did_oauth_provider
|
|
76
|
+
|
|
77
|
+
oauth = create_agent_did_oauth_provider(
|
|
78
|
+
server_url="https://mcp.example.com/mcp",
|
|
79
|
+
client_id="https://agent.example.com/oauth/client.json", # CIMD URL, or a pre-registered id
|
|
80
|
+
issuer="https://auth.example.com", # the authorization server's issuer
|
|
81
|
+
verification_method_id=f"{did}#key-1", # an `authentication` key
|
|
82
|
+
agent_private_key=private_key_hex, # or signer=<KMS / HSM AgentSigner>
|
|
83
|
+
storage=token_storage,
|
|
84
|
+
)
|
|
85
|
+
auth = AgentDidMcpAuth(
|
|
86
|
+
agent_identity=identity,
|
|
87
|
+
server_url="https://mcp.example.com/mcp",
|
|
88
|
+
agent_did=did,
|
|
89
|
+
verification_method_id=f"{did}#key-1", # an `assertionMethod` key
|
|
90
|
+
agent_private_key=private_key_hex,
|
|
91
|
+
inner=oauth,
|
|
92
|
+
)
|
|
93
|
+
async with httpx2.AsyncClient(auth=auth) as http_client:
|
|
94
|
+
async with streamable_http_client("https://mcp.example.com/mcp", http_client=http_client) as streams:
|
|
95
|
+
async with ClientSession(streams[0], streams[1]) as session:
|
|
96
|
+
await session.initialize()
|
|
97
|
+
await session.call_tool("whoami", {})
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The authorization server must know the client's keys. With CIMD it fetches the `client_id` URL: serve it with `client_metadata_routes(client_id=..., client_name=..., did_document=lambda: runtime.document, jwks_path="/oauth/jwks.json")`, and serve it again after a key rotation (authorization servers cache it). An authorization server that knows Agent-DID can instead check the assertion against the DID document with `AgentDidClient.verify_client_assertion`.
|
|
101
|
+
|
|
102
|
+
With a capability, pass `capability=` (a capability whose `controller` is the agent DID) and a `capabilityInvocation` key as `verification_method_id`.
|
|
103
|
+
|
|
104
|
+
## Example
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
python -m examples.mcp_signed_tool_call
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
A real `mcp` client calls a tool on a real `MCPServer` in process; the tool answers with the caller's verified DID.
|
|
111
|
+
|
|
112
|
+
## Limits
|
|
113
|
+
|
|
114
|
+
- Streamable HTTP only: stdio has no HTTP request to sign.
|
|
115
|
+
- Python only; a TypeScript MCP integration is planned after 1.0 (ADR-008).
|
|
116
|
+
- The middleware verifies requests; it does not sign responses.
|
|
117
|
+
- No claim of conformance with the MCP specification: the tests run the official `mcp` SDK client and server in process.
|
|
118
|
+
|
|
119
|
+
## Tests
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
python -m pytest tests -q # from integrations/mcp
|
|
123
|
+
npm run test:mcp # from the repository root
|
|
124
|
+
```
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/agent_did_mcp/__init__.py
|
|
4
|
+
src/agent_did_mcp/client.py
|
|
5
|
+
src/agent_did_mcp/metadata.py
|
|
6
|
+
src/agent_did_mcp/server.py
|
|
7
|
+
src/agent_did_mcp.egg-info/PKG-INFO
|
|
8
|
+
src/agent_did_mcp.egg-info/SOURCES.txt
|
|
9
|
+
src/agent_did_mcp.egg-info/dependency_links.txt
|
|
10
|
+
src/agent_did_mcp.egg-info/requires.txt
|
|
11
|
+
src/agent_did_mcp.egg-info/top_level.txt
|
|
12
|
+
tests/test_client_and_metadata.py
|
|
13
|
+
tests/test_end_to_end.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
agent_did_mcp
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""Capability invocations through the middleware, composition with an inner auth (OAuth), DID client assertions and
|
|
2
|
+
the CIMD / JWKS routes."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import AsyncGenerator, Generator
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import httpx2
|
|
11
|
+
import pytest
|
|
12
|
+
from agent_did_sdk import (
|
|
13
|
+
AgentIdentity,
|
|
14
|
+
AgentIdentityConfig,
|
|
15
|
+
CreateAgentParams,
|
|
16
|
+
CreateAgentResult,
|
|
17
|
+
HttpTargetValidationOptions,
|
|
18
|
+
InMemoryAgentRegistry,
|
|
19
|
+
LocalKeySigner,
|
|
20
|
+
)
|
|
21
|
+
from starlette.applications import Starlette
|
|
22
|
+
from starlette.requests import Request
|
|
23
|
+
from starlette.responses import JSONResponse
|
|
24
|
+
from starlette.routing import Route
|
|
25
|
+
|
|
26
|
+
from agent_did_mcp import (
|
|
27
|
+
AgentDidMcpAuth,
|
|
28
|
+
AgentDidSignatureMiddleware,
|
|
29
|
+
agent_did_assertion_provider,
|
|
30
|
+
client_metadata_routes,
|
|
31
|
+
get_agent_did_principal,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
BASE = "https://mcp.example.com"
|
|
35
|
+
URL = f"{BASE}/mcp"
|
|
36
|
+
AS_ISSUER = "https://auth.example.com"
|
|
37
|
+
FAR = "2099-01-01T00:00:00Z"
|
|
38
|
+
PRIVATE = HttpTargetValidationOptions(allow_private_targets=True)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
async def _agent(identity: AgentIdentity, name: str, relationships: list[str] | None = None) -> CreateAgentResult:
|
|
42
|
+
return await identity.create(
|
|
43
|
+
CreateAgentParams(name=name, additional_verification_relationships=relationships or []) # type: ignore[arg-type]
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _echo_app() -> Starlette:
|
|
48
|
+
async def echo(request: Request) -> JSONResponse:
|
|
49
|
+
principal = get_agent_did_principal(request)
|
|
50
|
+
body = await request.body()
|
|
51
|
+
return JSONResponse(
|
|
52
|
+
{
|
|
53
|
+
"did": principal.did if principal else None,
|
|
54
|
+
"capability": principal.capability_id if principal else None,
|
|
55
|
+
"body": body.decode(),
|
|
56
|
+
"authorization": request.headers.get("authorization"),
|
|
57
|
+
}
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
return Starlette(routes=[Route("/mcp", echo, methods=["POST"]), Route("/public", echo, methods=["POST"])])
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@pytest.mark.asyncio
|
|
64
|
+
async def test_a_capability_invocation_passes_and_names_the_capability() -> None:
|
|
65
|
+
AgentIdentity.set_registry(InMemoryAgentRegistry())
|
|
66
|
+
identity = AgentIdentity(AgentIdentityConfig(controller_signer=LocalKeySigner.generate()[0]))
|
|
67
|
+
owner = await _agent(identity, "Owner", ["capabilityDelegation"])
|
|
68
|
+
caller = await _agent(identity, "Caller", ["capabilityInvocation"])
|
|
69
|
+
capability = await identity.client.create_capability(
|
|
70
|
+
invocation_target=URL,
|
|
71
|
+
controller=caller.document.id,
|
|
72
|
+
expires=FAR,
|
|
73
|
+
allowed_action=["POST"],
|
|
74
|
+
verification_method_id=f"{owner.document.id}#key-1",
|
|
75
|
+
signer=LocalKeySigner(owner.agent_private_key),
|
|
76
|
+
)
|
|
77
|
+
roots = {URL: [owner.document.id]}
|
|
78
|
+
wrapped = AgentDidSignatureMiddleware(
|
|
79
|
+
_echo_app(), agent_identity=identity, public_base_url=BASE, root_controllers=roots, require_capability=True
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
def auth(with_capability: bool) -> AgentDidMcpAuth:
|
|
83
|
+
return AgentDidMcpAuth(
|
|
84
|
+
agent_identity=identity,
|
|
85
|
+
server_url=URL,
|
|
86
|
+
agent_did=caller.document.id,
|
|
87
|
+
verification_method_id=f"{caller.document.id}#key-1",
|
|
88
|
+
agent_private_key=caller.agent_private_key,
|
|
89
|
+
capability=capability if with_capability else None,
|
|
90
|
+
http_security=PRIVATE,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
async with httpx2.AsyncClient(transport=httpx2.ASGITransport(app=wrapped), auth=auth(True)) as client:
|
|
94
|
+
response = await client.post(URL, content=b'{"x":1}')
|
|
95
|
+
assert response.status_code == 200
|
|
96
|
+
data = json.loads(response.content)
|
|
97
|
+
assert (data["did"], data["capability"], data["body"]) == (caller.document.id, capability["id"], '{"x":1}')
|
|
98
|
+
|
|
99
|
+
async with httpx2.AsyncClient(transport=httpx2.ASGITransport(app=wrapped), auth=auth(False)) as client:
|
|
100
|
+
refused = await client.post(URL, content=b"{}")
|
|
101
|
+
assert (refused.status_code, json.loads(refused.content)["reason"]) == (403, "capability_required")
|
|
102
|
+
|
|
103
|
+
with pytest.raises(ValueError):
|
|
104
|
+
AgentDidSignatureMiddleware(_echo_app(), agent_identity=identity, require_capability=True)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _BearerThenToken(httpx2.Auth):
|
|
108
|
+
"""Stands in for the OAuth provider: a token request to the authorization server, then the request with a token."""
|
|
109
|
+
|
|
110
|
+
def sync_auth_flow(self, request: httpx2.Request) -> Generator[httpx2.Request, httpx2.Response, None]:
|
|
111
|
+
raise NotImplementedError
|
|
112
|
+
|
|
113
|
+
async def async_auth_flow(self, request: httpx2.Request) -> AsyncGenerator[httpx2.Request, httpx2.Response]:
|
|
114
|
+
token_response = yield httpx2.Request("POST", f"{AS_ISSUER}/token", content=b"grant_type=client_credentials")
|
|
115
|
+
request.headers["authorization"] = f"Bearer {json.loads(token_response.content)['access_token']}"
|
|
116
|
+
yield request
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@pytest.mark.asyncio
|
|
120
|
+
async def test_only_requests_to_the_mcp_origin_are_signed_after_the_inner_auth() -> None:
|
|
121
|
+
AgentIdentity.set_registry(InMemoryAgentRegistry())
|
|
122
|
+
identity = AgentIdentity(AgentIdentityConfig(controller_signer=LocalKeySigner.generate()[0]))
|
|
123
|
+
agent = await _agent(identity, "Agent")
|
|
124
|
+
seen: list[httpx2.Request] = []
|
|
125
|
+
wrapped = AgentDidSignatureMiddleware(_echo_app(), agent_identity=identity, public_base_url=BASE)
|
|
126
|
+
mcp_transport = httpx2.ASGITransport(app=wrapped)
|
|
127
|
+
|
|
128
|
+
class Router(httpx2.AsyncBaseTransport):
|
|
129
|
+
async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response:
|
|
130
|
+
seen.append(request)
|
|
131
|
+
if request.url.host == "auth.example.com":
|
|
132
|
+
return httpx2.Response(200, json={"access_token": "t0k"})
|
|
133
|
+
return await mcp_transport.handle_async_request(request)
|
|
134
|
+
|
|
135
|
+
auth = AgentDidMcpAuth(
|
|
136
|
+
agent_identity=identity,
|
|
137
|
+
server_url=URL,
|
|
138
|
+
agent_did=agent.document.id,
|
|
139
|
+
verification_method_id=f"{agent.document.id}#key-1",
|
|
140
|
+
agent_private_key=agent.agent_private_key,
|
|
141
|
+
inner=_BearerThenToken(),
|
|
142
|
+
http_security=PRIVATE,
|
|
143
|
+
)
|
|
144
|
+
async with httpx2.AsyncClient(transport=Router(), auth=auth) as client:
|
|
145
|
+
response = await client.post(URL, content=b"{}")
|
|
146
|
+
|
|
147
|
+
assert response.status_code == 200
|
|
148
|
+
assert json.loads(response.content)["did"] == agent.document.id
|
|
149
|
+
assert json.loads(response.content)["authorization"] == "Bearer t0k"
|
|
150
|
+
token_request, mcp_request = seen
|
|
151
|
+
assert "signature" not in token_request.headers
|
|
152
|
+
assert "signature" in mcp_request.headers and "agent-did" in mcp_request.headers
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@pytest.mark.asyncio
|
|
156
|
+
async def test_unprotected_paths_pass_through_and_large_bodies_are_refused() -> None:
|
|
157
|
+
AgentIdentity.set_registry(InMemoryAgentRegistry())
|
|
158
|
+
identity = AgentIdentity(AgentIdentityConfig(controller_signer=LocalKeySigner.generate()[0]))
|
|
159
|
+
wrapped = AgentDidSignatureMiddleware(_echo_app(), agent_identity=identity, max_body_bytes=4)
|
|
160
|
+
async with httpx2.AsyncClient(transport=httpx2.ASGITransport(app=wrapped)) as client:
|
|
161
|
+
public = await client.post(f"{BASE}/public", content=b"{}")
|
|
162
|
+
large = await client.post(URL, content=b"0123456789")
|
|
163
|
+
assert public.status_code == 200 and json.loads(public.content)["did"] is None
|
|
164
|
+
assert (large.status_code, json.loads(large.content)["reason"]) == (413, "body_too_large")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@pytest.mark.asyncio
|
|
168
|
+
async def test_the_assertion_provider_signs_a_client_assertion_the_sdk_verifies() -> None:
|
|
169
|
+
AgentIdentity.set_registry(InMemoryAgentRegistry())
|
|
170
|
+
identity = AgentIdentity(AgentIdentityConfig(controller_signer=LocalKeySigner.generate()[0]))
|
|
171
|
+
agent = await _agent(identity, "Agent")
|
|
172
|
+
client_id = "https://agent.example.com/oauth/client.json"
|
|
173
|
+
provider = agent_did_assertion_provider(
|
|
174
|
+
client_id=client_id,
|
|
175
|
+
verification_method_id=f"{agent.document.id}#key-1",
|
|
176
|
+
agent_private_key=agent.agent_private_key,
|
|
177
|
+
)
|
|
178
|
+
assertion = await provider(AS_ISSUER)
|
|
179
|
+
result = await identity.client.verify_client_assertion(
|
|
180
|
+
assertion, issuer=AS_ISSUER, client_id=client_id, did=agent.document.id
|
|
181
|
+
)
|
|
182
|
+
assert result.ok, result.reason
|
|
183
|
+
with pytest.raises(ValueError):
|
|
184
|
+
agent_did_assertion_provider(client_id=client_id, verification_method_id="x")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@pytest.mark.asyncio
|
|
188
|
+
async def test_metadata_routes_serve_the_cimd_and_jwks() -> None:
|
|
189
|
+
AgentIdentity.set_registry(InMemoryAgentRegistry())
|
|
190
|
+
identity = AgentIdentity(AgentIdentityConfig(controller_signer=LocalKeySigner.generate()[0]))
|
|
191
|
+
agent = await _agent(identity, "Agent")
|
|
192
|
+
client_id = "https://agent.example.com/oauth/client.json"
|
|
193
|
+
app = Starlette(
|
|
194
|
+
routes=client_metadata_routes(
|
|
195
|
+
client_id=client_id,
|
|
196
|
+
client_name="Agent",
|
|
197
|
+
did_document=lambda: agent.document,
|
|
198
|
+
jwks_path="/oauth/jwks.json",
|
|
199
|
+
)
|
|
200
|
+
)
|
|
201
|
+
async with httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app)) as client:
|
|
202
|
+
metadata: dict[str, Any] = json.loads((await client.get(client_id)).content)
|
|
203
|
+
jwks: dict[str, Any] = json.loads((await client.get("https://agent.example.com/oauth/jwks.json")).content)
|
|
204
|
+
assert metadata["client_id"] == client_id
|
|
205
|
+
assert metadata["token_endpoint_auth_method"] == "private_key_jwt"
|
|
206
|
+
assert metadata["jwks_uri"] == "https://agent.example.com/oauth/jwks.json"
|
|
207
|
+
assert jwks["keys"][0]["kid"] == f"{agent.document.id}#key-1"
|
|
208
|
+
with pytest.raises(ValueError):
|
|
209
|
+
client_metadata_routes(
|
|
210
|
+
client_id="http://agent.example.com/c.json", client_name="A", did_document=lambda: agent.document
|
|
211
|
+
)
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""End to end: a real ``mcp`` client and ``MCPServer`` over Streamable HTTP (in process, ASGI), with Agent-DID request
|
|
2
|
+
signatures checked by the middleware and the verified DID read by a tool."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import contextlib
|
|
7
|
+
import json
|
|
8
|
+
from collections.abc import AsyncIterator
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import httpx2
|
|
12
|
+
import pytest
|
|
13
|
+
from agent_did_sdk import (
|
|
14
|
+
AgentIdentity,
|
|
15
|
+
AgentIdentityConfig,
|
|
16
|
+
CreateAgentParams,
|
|
17
|
+
CreateAgentResult,
|
|
18
|
+
HttpTargetValidationOptions,
|
|
19
|
+
InMemoryAgentRegistry,
|
|
20
|
+
LocalKeySigner,
|
|
21
|
+
)
|
|
22
|
+
from mcp.client.session import ClientSession
|
|
23
|
+
from mcp.client.streamable_http import streamable_http_client
|
|
24
|
+
from mcp.server.mcpserver import Context, MCPServer
|
|
25
|
+
from starlette.types import ASGIApp
|
|
26
|
+
|
|
27
|
+
from agent_did_mcp import AgentDidMcpAuth, AgentDidSignatureMiddleware, get_agent_did_principal
|
|
28
|
+
|
|
29
|
+
BASE = "https://mcp.example.com"
|
|
30
|
+
URL = f"{BASE}/mcp"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def _agent(name: str) -> tuple[AgentIdentity, CreateAgentResult]:
|
|
34
|
+
identity = AgentIdentity(AgentIdentityConfig(controller_signer=LocalKeySigner.generate()[0]))
|
|
35
|
+
return identity, await identity.create(CreateAgentParams(name=name, core_model="m", system_prompt="p"))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _server() -> MCPServer:
|
|
39
|
+
server = MCPServer("whoami")
|
|
40
|
+
|
|
41
|
+
@server.tool()
|
|
42
|
+
def whoami(ctx: Context) -> str: # type: ignore[type-arg]
|
|
43
|
+
principal = get_agent_did_principal(ctx)
|
|
44
|
+
return "anonymous" if principal is None else principal.did
|
|
45
|
+
|
|
46
|
+
return server
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@contextlib.asynccontextmanager
|
|
50
|
+
async def _running(app: Any) -> AsyncIterator[None]:
|
|
51
|
+
async with app.router.lifespan_context(app):
|
|
52
|
+
yield
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _auth(identity: AgentIdentity, runtime: CreateAgentResult) -> AgentDidMcpAuth:
|
|
56
|
+
key_id = (runtime.document.assertion_method or [""])[0]
|
|
57
|
+
return AgentDidMcpAuth(
|
|
58
|
+
agent_identity=identity,
|
|
59
|
+
server_url=URL,
|
|
60
|
+
agent_did=runtime.document.id,
|
|
61
|
+
verification_method_id=key_id,
|
|
62
|
+
agent_private_key=runtime.agent_private_key,
|
|
63
|
+
http_security=HttpTargetValidationOptions(allow_private_targets=True),
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
async def _call_whoami(wrapped: ASGIApp, auth: httpx2.Auth | None) -> str:
|
|
68
|
+
async with httpx2.AsyncClient(transport=httpx2.ASGITransport(app=wrapped), auth=auth) as http_client:
|
|
69
|
+
async with streamable_http_client(URL, http_client=http_client) as streams:
|
|
70
|
+
async with ClientSession(streams[0], streams[1]) as session:
|
|
71
|
+
await session.initialize()
|
|
72
|
+
result = await session.call_tool("whoami", {})
|
|
73
|
+
return str(result.content[0].text) # type: ignore[union-attr]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@pytest.mark.asyncio
|
|
77
|
+
async def test_a_signed_mcp_session_reaches_the_tool_with_the_verified_did() -> None:
|
|
78
|
+
AgentIdentity.set_registry(InMemoryAgentRegistry())
|
|
79
|
+
server_identity, _ = await _agent("Server")
|
|
80
|
+
client_identity, client_runtime = await _agent("Client")
|
|
81
|
+
app = _server().streamable_http_app(stateless_http=True, json_response=True, host="mcp.example.com")
|
|
82
|
+
wrapped = AgentDidSignatureMiddleware(app, agent_identity=server_identity, public_base_url=BASE)
|
|
83
|
+
async with _running(app):
|
|
84
|
+
assert await _call_whoami(wrapped, _auth(client_identity, client_runtime)) == client_runtime.document.id
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@pytest.mark.asyncio
|
|
88
|
+
async def test_an_unsigned_request_is_rejected_with_401() -> None:
|
|
89
|
+
AgentIdentity.set_registry(InMemoryAgentRegistry())
|
|
90
|
+
server_identity, _ = await _agent("Server")
|
|
91
|
+
app = _server().streamable_http_app(stateless_http=True, json_response=True, host="mcp.example.com")
|
|
92
|
+
wrapped = AgentDidSignatureMiddleware(app, agent_identity=server_identity, public_base_url=BASE)
|
|
93
|
+
async with httpx2.AsyncClient(transport=httpx2.ASGITransport(app=wrapped)) as http_client:
|
|
94
|
+
response = await http_client.post(URL, content=b"{}", headers={"content-type": "application/json"})
|
|
95
|
+
assert response.status_code == 401
|
|
96
|
+
assert json.loads(response.content)["reason"] == "missing_headers"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@pytest.mark.asyncio
|
|
100
|
+
async def test_allowed_dids_refuse_other_agents() -> None:
|
|
101
|
+
AgentIdentity.set_registry(InMemoryAgentRegistry())
|
|
102
|
+
server_identity, _ = await _agent("Server")
|
|
103
|
+
client_identity, client_runtime = await _agent("Client")
|
|
104
|
+
app = _server().streamable_http_app(stateless_http=True, json_response=True, host="mcp.example.com")
|
|
105
|
+
wrapped = AgentDidSignatureMiddleware(
|
|
106
|
+
app, agent_identity=server_identity, public_base_url=BASE, allowed_dids=["did:webvh:Qm:other.example"]
|
|
107
|
+
)
|
|
108
|
+
auth = _auth(client_identity, client_runtime)
|
|
109
|
+
async with _running(app):
|
|
110
|
+
async with httpx2.AsyncClient(transport=httpx2.ASGITransport(app=wrapped), auth=auth) as http_client:
|
|
111
|
+
response = await http_client.post(URL, content=b"{}", headers={"content-type": "application/json"})
|
|
112
|
+
assert response.status_code == 401
|
|
113
|
+
assert json.loads(response.content)["reason"] == "did_not_allowed"
|