agentic-platform-sdk 0.1.0__py3-none-any.whl
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.
- agentic_platform_sdk/__init__.py +9 -0
- agentic_platform_sdk/_a2a.py +133 -0
- agentic_platform_sdk/_client.py +152 -0
- agentic_platform_sdk/_contract.py +72 -0
- agentic_platform_sdk/_generated/__init__.py +0 -0
- agentic_platform_sdk/_generated/_base.py +20 -0
- agentic_platform_sdk/_generated/models.py +698 -0
- agentic_platform_sdk/_paging.py +117 -0
- agentic_platform_sdk/_spec/call_areas.json +13 -0
- agentic_platform_sdk/_spec/chat-events.schema.json +371 -0
- agentic_platform_sdk/_spec/errors.json +2365 -0
- agentic_platform_sdk/_spec/operations.json +230 -0
- agentic_platform_sdk/_transport.py +630 -0
- agentic_platform_sdk/_util.py +133 -0
- agentic_platform_sdk/agents.py +793 -0
- agentic_platform_sdk/approvals.py +66 -0
- agentic_platform_sdk/auth.py +336 -0
- agentic_platform_sdk/chat.py +599 -0
- agentic_platform_sdk/datasets.py +69 -0
- agentic_platform_sdk/errors.py +204 -0
- agentic_platform_sdk/kb.py +288 -0
- agentic_platform_sdk/llm.py +40 -0
- agentic_platform_sdk/me.py +28 -0
- agentic_platform_sdk/models.py +91 -0
- agentic_platform_sdk/ontology.py +209 -0
- agentic_platform_sdk/py.typed +0 -0
- agentic_platform_sdk/testing/__init__.py +19 -0
- agentic_platform_sdk/testing/conformance.py +803 -0
- agentic_platform_sdk/testing/fake.py +902 -0
- agentic_platform_sdk/testing/standin.py +165 -0
- agentic_platform_sdk/toolchains.py +137 -0
- agentic_platform_sdk/tools/__init__.py +70 -0
- agentic_platform_sdk/tools/_jcs.py +218 -0
- agentic_platform_sdk/tools/asgi.py +228 -0
- agentic_platform_sdk/tools/mcp.py +751 -0
- agentic_platform_sdk/tools/verify.py +379 -0
- agentic_platform_sdk/vision.py +300 -0
- agentic_platform_sdk-0.1.0.dist-info/METADATA +226 -0
- agentic_platform_sdk-0.1.0.dist-info/RECORD +41 -0
- agentic_platform_sdk-0.1.0.dist-info/WHEEL +4 -0
- agentic_platform_sdk-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""The ASGI layer in front of an app's MCP endpoint (spec §4.7.5): no request reaches the MCP
|
|
2
|
+
server unless its bearer token verified.
|
|
3
|
+
|
|
4
|
+
It knows JSON-RPC but not the MCP package, so it wraps an inner ASGI app that serves MCP over
|
|
5
|
+
**stateless** Streamable HTTP (every request independent, no ``Mcp-Session-Id``; `AgenticToolServer`
|
|
6
|
+
in ``tools/mcp.py`` pins this mode on the official SDK). One HTTP request carries one
|
|
7
|
+
token, verified once, over
|
|
8
|
+
the bytes as sent:
|
|
9
|
+
|
|
10
|
+
* a ``tools/call`` needs a ``purpose: "call"`` token whose ``tool`` is the name in the body and
|
|
11
|
+
whose ``app_ctx_sha256`` is the hash of ``params._meta["agentic.app_context"]``; the verified
|
|
12
|
+
`ToolCaller` is set in `current_caller` for the inner app's handler;
|
|
13
|
+
* only ``initialize``, ``notifications/initialized``, ``tools/list`` and ``ping`` (and a bodyless
|
|
14
|
+
GET / DELETE) are served with a ``purpose: "sync"`` token (no user in it). Any other method, a
|
|
15
|
+
body that is not a JSON object or array, a batch holding a call, is refused.
|
|
16
|
+
|
|
17
|
+
`current_caller` is a context variable: it is right only while the inner app runs the tool handler
|
|
18
|
+
in the request's own task context, which is what stateless mode does. A **stateful** server runs
|
|
19
|
+
handlers in a session task created by the first request, so a later call would see that request's
|
|
20
|
+
caller (None, or another user's): do not put `CallbackAuth` in front of one.
|
|
21
|
+
|
|
22
|
+
Only ``http`` and ``lifespan`` scopes are served: a ``websocket`` is closed (1008) and nothing else
|
|
23
|
+
reaches the inner app.
|
|
24
|
+
|
|
25
|
+
A refusal is HTTP 401 with an empty JSON body and ``WWW-Authenticate: Bearer``: no code, no detail
|
|
26
|
+
(the app logs the code through ``on_refused``).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import json
|
|
32
|
+
import logging
|
|
33
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
34
|
+
from contextvars import ContextVar
|
|
35
|
+
from typing import Any
|
|
36
|
+
|
|
37
|
+
from .verify import (
|
|
38
|
+
APP_CONTEXT_META_KEY,
|
|
39
|
+
PURPOSE_CALL,
|
|
40
|
+
PURPOSE_SYNC,
|
|
41
|
+
AsyncReplayStore,
|
|
42
|
+
CallbackRefused,
|
|
43
|
+
InMemoryReplayStore,
|
|
44
|
+
ReplayStore,
|
|
45
|
+
ToolCaller,
|
|
46
|
+
_checked_secrets,
|
|
47
|
+
averify_callback_token,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
log = logging.getLogger("agentic_platform_sdk.tools")
|
|
51
|
+
|
|
52
|
+
#: The caller of the tool call being handled (None outside a verified ``tools/call``).
|
|
53
|
+
current_caller: ContextVar[ToolCaller | None] = ContextVar("agentic_tool_caller", default=None)
|
|
54
|
+
|
|
55
|
+
Scope = dict[str, Any]
|
|
56
|
+
Receive = Callable[[], Awaitable[dict[str, Any]]]
|
|
57
|
+
Send = Callable[[dict[str, Any]], Awaitable[None]]
|
|
58
|
+
MAX_BODY_BYTES = 1024 * 1024
|
|
59
|
+
#: The only methods a ``sync`` token may carry. Everything else that is not a ``tools/call`` is
|
|
60
|
+
#: refused until it has a purpose of its own (``resources/read``, ``prompts/get``,
|
|
61
|
+
#: ``completion/complete`` run app code with no user in the token).
|
|
62
|
+
SYNC_METHODS = frozenset({"initialize", "notifications/initialized", "tools/list", "ping"})
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class _Refuse(Exception):
|
|
66
|
+
def __init__(self, code: str, status: int = 401) -> None:
|
|
67
|
+
super().__init__(code)
|
|
68
|
+
self.code, self.status = code, status
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class CallbackAuth:
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
app: Callable[[Scope, Receive, Send], Awaitable[None]],
|
|
75
|
+
*,
|
|
76
|
+
audience: str,
|
|
77
|
+
secrets: Sequence[str] | Callable[[], Sequence[str]],
|
|
78
|
+
replay: ReplayStore | AsyncReplayStore | None = None,
|
|
79
|
+
max_body_bytes: int = MAX_BODY_BYTES,
|
|
80
|
+
on_refused: Callable[[str], None] | None = None,
|
|
81
|
+
) -> None:
|
|
82
|
+
self.app = app
|
|
83
|
+
self.audience = audience
|
|
84
|
+
if not callable(secrets):
|
|
85
|
+
_checked_secrets(secrets) # a bare str / a short secret fails here, not per request
|
|
86
|
+
self._secrets = secrets
|
|
87
|
+
self.replay: ReplayStore | AsyncReplayStore = (
|
|
88
|
+
replay if replay is not None else InMemoryReplayStore()
|
|
89
|
+
)
|
|
90
|
+
self.max_body_bytes = max_body_bytes
|
|
91
|
+
self.on_refused = on_refused
|
|
92
|
+
|
|
93
|
+
def _live_secrets(self) -> Sequence[str]:
|
|
94
|
+
return self._secrets() if callable(self._secrets) else self._secrets
|
|
95
|
+
|
|
96
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
97
|
+
kind = scope["type"]
|
|
98
|
+
if kind == "lifespan":
|
|
99
|
+
await self.app(scope, receive, send)
|
|
100
|
+
return
|
|
101
|
+
if kind == "websocket":
|
|
102
|
+
await send({"type": "websocket.close", "code": 1008})
|
|
103
|
+
return
|
|
104
|
+
if kind != "http":
|
|
105
|
+
return
|
|
106
|
+
try:
|
|
107
|
+
token = _bearer(
|
|
108
|
+
scope
|
|
109
|
+
) # before the body: an unauthenticated client makes us buffer nothing
|
|
110
|
+
body = await self._body(receive)
|
|
111
|
+
caller = await self._verify(token, body)
|
|
112
|
+
except _Refuse as refused:
|
|
113
|
+
self._note(refused.code)
|
|
114
|
+
await self._answer(send, refused.status)
|
|
115
|
+
return
|
|
116
|
+
except CallbackRefused as refused:
|
|
117
|
+
self._note(refused.code)
|
|
118
|
+
await self._answer(send, 401)
|
|
119
|
+
return
|
|
120
|
+
sent = False
|
|
121
|
+
|
|
122
|
+
async def replay_body() -> dict[str, Any]:
|
|
123
|
+
nonlocal sent
|
|
124
|
+
if sent:
|
|
125
|
+
return await receive()
|
|
126
|
+
sent = True
|
|
127
|
+
return {"type": "http.request", "body": body, "more_body": False}
|
|
128
|
+
|
|
129
|
+
token = current_caller.set(caller)
|
|
130
|
+
try:
|
|
131
|
+
await self.app(scope, replay_body, send)
|
|
132
|
+
finally:
|
|
133
|
+
current_caller.reset(token)
|
|
134
|
+
|
|
135
|
+
def _note(self, code: str) -> None:
|
|
136
|
+
log.warning("app tool callback refused: %s", code)
|
|
137
|
+
if self.on_refused:
|
|
138
|
+
self.on_refused(code)
|
|
139
|
+
|
|
140
|
+
async def _body(self, receive: Receive) -> bytes:
|
|
141
|
+
chunks: list[bytes] = []
|
|
142
|
+
size = 0
|
|
143
|
+
while True:
|
|
144
|
+
message = await receive()
|
|
145
|
+
if message["type"] == "http.disconnect":
|
|
146
|
+
raise _Refuse("callback.malformed")
|
|
147
|
+
chunk = message.get("body", b"")
|
|
148
|
+
size += len(chunk)
|
|
149
|
+
if size > self.max_body_bytes:
|
|
150
|
+
raise _Refuse("callback.malformed", 413)
|
|
151
|
+
chunks.append(chunk)
|
|
152
|
+
if not message.get("more_body"):
|
|
153
|
+
return b"".join(chunks)
|
|
154
|
+
|
|
155
|
+
async def _verify(self, token: str, body: bytes) -> ToolCaller | None:
|
|
156
|
+
tool, app_context = _call_of(body)
|
|
157
|
+
purpose = PURPOSE_CALL if tool is not None else PURPOSE_SYNC
|
|
158
|
+
return await averify_callback_token(
|
|
159
|
+
token,
|
|
160
|
+
secrets=self._live_secrets(),
|
|
161
|
+
audience=self.audience,
|
|
162
|
+
tool=tool,
|
|
163
|
+
app_context=app_context,
|
|
164
|
+
replay=self.replay,
|
|
165
|
+
purpose=purpose,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
@staticmethod
|
|
169
|
+
async def _answer(send: Send, status: int) -> None:
|
|
170
|
+
await send(
|
|
171
|
+
{
|
|
172
|
+
"type": "http.response.start",
|
|
173
|
+
"status": status,
|
|
174
|
+
"headers": [
|
|
175
|
+
(b"content-type", b"application/json"),
|
|
176
|
+
(b"www-authenticate", b"Bearer"),
|
|
177
|
+
(b"cache-control", b"no-store"),
|
|
178
|
+
],
|
|
179
|
+
}
|
|
180
|
+
)
|
|
181
|
+
await send({"type": "http.response.body", "body": b"{}"})
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _bearer(scope: Scope) -> str:
|
|
185
|
+
values = [v for k, v in scope.get("headers", []) if k == b"authorization"]
|
|
186
|
+
if len(values) != 1:
|
|
187
|
+
raise CallbackRefused("callback.malformed")
|
|
188
|
+
scheme, _, token = values[0].decode("latin-1").partition(" ")
|
|
189
|
+
if scheme.lower() != "bearer" or not token.strip():
|
|
190
|
+
raise CallbackRefused("callback.malformed")
|
|
191
|
+
return token.strip()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _call_of(body: bytes) -> tuple[str | None, dict[str, Any] | None]:
|
|
195
|
+
"""``(tool, app_context)`` when the body is a ``tools/call``, ``(None, None)`` when it is an
|
|
196
|
+
empty body or only `SYNC_METHODS`. Refuses (``callback.malformed``) a body that is not strict
|
|
197
|
+
UTF-8
|
|
198
|
+
JSON holding an object or a non-empty array of objects with a string ``method``, and any other
|
|
199
|
+
method (``callback.wrong_purpose``): the classification fails closed."""
|
|
200
|
+
if not body:
|
|
201
|
+
return None, None
|
|
202
|
+
try:
|
|
203
|
+
doc = json.loads(body.decode("utf-8"))
|
|
204
|
+
except (ValueError, RecursionError):
|
|
205
|
+
raise CallbackRefused("callback.malformed") from None
|
|
206
|
+
messages = doc if isinstance(doc, list) else [doc]
|
|
207
|
+
if not messages or not all(
|
|
208
|
+
isinstance(m, dict) and isinstance(m.get("method"), str) for m in messages
|
|
209
|
+
):
|
|
210
|
+
raise CallbackRefused("callback.malformed")
|
|
211
|
+
calls = [m for m in messages if m["method"] == "tools/call"]
|
|
212
|
+
if not calls:
|
|
213
|
+
if any(m["method"] not in SYNC_METHODS for m in messages):
|
|
214
|
+
raise CallbackRefused("callback.wrong_purpose")
|
|
215
|
+
return None, None
|
|
216
|
+
if len(messages) != 1:
|
|
217
|
+
# One token covers one call: a batch that holds a call is refused (the token cannot name two
|
|
218
|
+
# tools).
|
|
219
|
+
raise CallbackRefused("callback.wrong_tool")
|
|
220
|
+
params = calls[0].get("params")
|
|
221
|
+
name = params.get("name") if isinstance(params, dict) else None
|
|
222
|
+
if not isinstance(name, str) or not name:
|
|
223
|
+
raise CallbackRefused("callback.malformed")
|
|
224
|
+
meta = params.get("_meta")
|
|
225
|
+
context = meta.get(APP_CONTEXT_META_KEY) if isinstance(meta, dict) else None
|
|
226
|
+
if context is not None and not isinstance(context, dict):
|
|
227
|
+
raise CallbackRefused("callback.context_mismatch")
|
|
228
|
+
return name, context
|