aiohttp-tiny-mcp 0.5.7__tar.gz → 0.5.9__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.
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/PKG-INFO +19 -1
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/README.md +18 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/pyproject.toml +5 -2
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/pyproject.toml.orig +2 -2
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/__init__.py +9 -0
- aiohttp_tiny_mcp-0.5.9/src/aiohttp_tiny_mcp/client/callback.py +113 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/http.py +62 -10
- aiohttp_tiny_mcp-0.5.9/src/aiohttp_tiny_mcp/client/loopback.py +107 -0
- aiohttp_tiny_mcp-0.5.9/src/aiohttp_tiny_mcp/client/oauth.py +674 -0
- aiohttp_tiny_mcp-0.5.9/src/aiohttp_tiny_mcp/client/oauth_helpers.py +96 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/console/console.js +188 -27
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/console/index.html +4 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/http.py +35 -2
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/sqlite.py +62 -33
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/LICENSE +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/auth/__init__.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/auth/jwt.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/__init__.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/base.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/stdio.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/console/__init__.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/console/console.css +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/console/oauth-callback.html +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/extensions/__init__.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/extensions/skills.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/oauth/__init__.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/oauth/github.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/oauth/provider.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/oauth/server.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/oauth/tokens.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/__init__.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/adapter.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/core.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/models.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/schema.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/selection.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/v2024_11_05.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/v2025_03_26.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/v2025_06_18.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/v2025_11_25.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/v2026_07_28.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/py.typed +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/__init__.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/dispatcher.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/exchange.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/registry.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/request_state.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/specs.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/sse.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/stdio.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/subscriptions.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/tasks.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/__init__.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/hub.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/namespaces.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/postgres.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/redis.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/sessions.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/testing.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/transport/__init__.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/transport/metadata.py +0 -0
- {aiohttp_tiny_mcp-0.5.7 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/transport/sse.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: aiohttp-tiny-mcp
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.9
|
|
4
4
|
Summary: Remote MCP server and client library for aiohttp
|
|
5
5
|
License-Expression: Apache-2.0
|
|
6
6
|
License-File: LICENSE
|
|
@@ -178,6 +178,12 @@ the five revisions, builds a form from each tool's schema, answers the
|
|
|
178
178
|
questions a handler asks, and shows every message either way. Static files from
|
|
179
179
|
this package need no build step or second process.
|
|
180
180
|
|
|
181
|
+
The console receives background MCP notifications by default. Its
|
|
182
|
+
**Notifications** checkbox controls resource updates, list changes, and extension
|
|
183
|
+
broadcasts shown in **Traffic**. See the
|
|
184
|
+
[console guide](https://mosquito.github.io/aiohttp-tiny-mcp/guide/console.html)
|
|
185
|
+
for subscription and reconnection behavior.
|
|
186
|
+
|
|
181
187
|
An MCP host that supports Streamable HTTP can connect to
|
|
182
188
|
`http://127.0.0.1:8080/mcp`. In an existing aiohttp service, use
|
|
183
189
|
`Endpoint(registry).setup(app, "/mcp")`. For a local subprocess transport,
|
|
@@ -190,6 +196,18 @@ from the client. Put irreversible work after the final question: some revisions
|
|
|
190
196
|
restart the handler when the answer arrives. Python locals are not persisted
|
|
191
197
|
automatically. See [Asking the user](https://mosquito.github.io/aiohttp-tiny-mcp/guide/asking.html).
|
|
192
198
|
|
|
199
|
+
## Team chat for agents
|
|
200
|
+
|
|
201
|
+
[MCP Chat](examples/mcp-chat/README.md) is a runnable team chat for AI agents
|
|
202
|
+
and people. Agents use MCP tools; people use the web UI. It provides channels,
|
|
203
|
+
direct messages, threads, subscriptions, persistent inboxes, and full-text
|
|
204
|
+
search within each organization. Live MCP notifications deliver updates, with
|
|
205
|
+
polling as a fallback. Optional JWT authentication binds each agent to an
|
|
206
|
+
organization and user, and Observe shows its activity.
|
|
207
|
+
|
|
208
|
+
The example has its own `pyproject.toml`, SQLite database, and setup guide for
|
|
209
|
+
Codex, Claude Code, Pi, Cursor, and VS Code.
|
|
210
|
+
|
|
193
211
|
## Call it from Python
|
|
194
212
|
|
|
195
213
|
The bundled `Client` is useful for integration tests or an application that
|
|
@@ -134,6 +134,12 @@ the five revisions, builds a form from each tool's schema, answers the
|
|
|
134
134
|
questions a handler asks, and shows every message either way. Static files from
|
|
135
135
|
this package need no build step or second process.
|
|
136
136
|
|
|
137
|
+
The console receives background MCP notifications by default. Its
|
|
138
|
+
**Notifications** checkbox controls resource updates, list changes, and extension
|
|
139
|
+
broadcasts shown in **Traffic**. See the
|
|
140
|
+
[console guide](https://mosquito.github.io/aiohttp-tiny-mcp/guide/console.html)
|
|
141
|
+
for subscription and reconnection behavior.
|
|
142
|
+
|
|
137
143
|
An MCP host that supports Streamable HTTP can connect to
|
|
138
144
|
`http://127.0.0.1:8080/mcp`. In an existing aiohttp service, use
|
|
139
145
|
`Endpoint(registry).setup(app, "/mcp")`. For a local subprocess transport,
|
|
@@ -146,6 +152,18 @@ from the client. Put irreversible work after the final question: some revisions
|
|
|
146
152
|
restart the handler when the answer arrives. Python locals are not persisted
|
|
147
153
|
automatically. See [Asking the user](https://mosquito.github.io/aiohttp-tiny-mcp/guide/asking.html).
|
|
148
154
|
|
|
155
|
+
## Team chat for agents
|
|
156
|
+
|
|
157
|
+
[MCP Chat](examples/mcp-chat/README.md) is a runnable team chat for AI agents
|
|
158
|
+
and people. Agents use MCP tools; people use the web UI. It provides channels,
|
|
159
|
+
direct messages, threads, subscriptions, persistent inboxes, and full-text
|
|
160
|
+
search within each organization. Live MCP notifications deliver updates, with
|
|
161
|
+
polling as a fallback. Optional JWT authentication binds each agent to an
|
|
162
|
+
organization and user, and Observe shows its activity.
|
|
163
|
+
|
|
164
|
+
The example has its own `pyproject.toml`, SQLite database, and setup guide for
|
|
165
|
+
Codex, Claude Code, Pi, Cursor, and VS Code.
|
|
166
|
+
|
|
149
167
|
## Call it from Python
|
|
150
168
|
|
|
151
169
|
The bundled `Client` is useful for integration tests or an application that
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "aiohttp-tiny-mcp"
|
|
3
|
-
version = "0.5.
|
|
3
|
+
version = "0.5.9"
|
|
4
4
|
description = "Remote MCP server and client library for aiohttp"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "Apache-2.0"
|
|
@@ -116,7 +116,10 @@ root = [
|
|
|
116
116
|
]
|
|
117
117
|
|
|
118
118
|
[tool.ty.src]
|
|
119
|
-
exclude = [
|
|
119
|
+
exclude = [
|
|
120
|
+
"examples/docker-mcp",
|
|
121
|
+
"examples/mcp-chat",
|
|
122
|
+
]
|
|
120
123
|
|
|
121
124
|
[build-system]
|
|
122
125
|
requires = ["uv_build>=0.12,<0.13"]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "aiohttp-tiny-mcp"
|
|
3
|
-
version = "0.5.
|
|
3
|
+
version = "0.5.9"
|
|
4
4
|
description = "Remote MCP server and client library for aiohttp"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "Apache-2.0"
|
|
@@ -116,4 +116,4 @@ root = ["src", "examples"]
|
|
|
116
116
|
|
|
117
117
|
[tool.ty.src]
|
|
118
118
|
# Checked separately with its own dependencies.
|
|
119
|
-
exclude = ["examples/docker-mcp"]
|
|
119
|
+
exclude = ["examples/docker-mcp", "examples/mcp-chat"]
|
|
@@ -14,7 +14,10 @@ from .auth import (
|
|
|
14
14
|
principal_from_claims,
|
|
15
15
|
)
|
|
16
16
|
from .client.base import ClientError, Elicitor
|
|
17
|
+
from .client.callback import OAuthCallback
|
|
17
18
|
from .client.http import Client
|
|
19
|
+
from .client.loopback import LoopbackCallback
|
|
20
|
+
from .client.oauth import AuthorizationRequired, OAuth, OAuthError, RegistrationRequired
|
|
18
21
|
from .client.stdio import StdioClient
|
|
19
22
|
from .extensions import Extension
|
|
20
23
|
from .protocol.core import (
|
|
@@ -55,6 +58,12 @@ from .transport.sse import SSEResponse
|
|
|
55
58
|
|
|
56
59
|
__all__ = [
|
|
57
60
|
"AdapterSet",
|
|
61
|
+
"OAuth",
|
|
62
|
+
"OAuthError",
|
|
63
|
+
"OAuthCallback",
|
|
64
|
+
"LoopbackCallback",
|
|
65
|
+
"AuthorizationRequired",
|
|
66
|
+
"RegistrationRequired",
|
|
58
67
|
"Answer",
|
|
59
68
|
"AnswerAction",
|
|
60
69
|
"AudioContent",
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""OAuth callbacks for an existing aiohttp application."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import hmac
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
|
|
9
|
+
from aiohttp import web
|
|
10
|
+
from yarl import URL
|
|
11
|
+
|
|
12
|
+
from .oauth import AuthorizationAttempt, OAuth
|
|
13
|
+
from .oauth_helpers import OAuthError
|
|
14
|
+
|
|
15
|
+
SUCCESS_HTML = """<!doctype html>
|
|
16
|
+
<html lang="en"><meta charset="utf-8"><title>Authorization complete</title>
|
|
17
|
+
<h1>Authorization complete</h1><p>You can close this window.</p></html>"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class OAuthCallback:
|
|
21
|
+
"""Mount a local or remote callback for one OAuth account context.
|
|
22
|
+
|
|
23
|
+
The application must authenticate the user before calling ``begin`` and
|
|
24
|
+
keep each user's context separate. The external HTTPS ``auth.redirect_uri``
|
|
25
|
+
can differ from the listener address behind a trusted reverse proxy.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, auth: OAuth, *, success_html: str = SUCCESS_HTML) -> None:
|
|
29
|
+
self.auth = auth
|
|
30
|
+
self.success_html = success_html
|
|
31
|
+
self.attempt: AuthorizationAttempt | None = None
|
|
32
|
+
self.outcome: asyncio.Future[Exception | None] | None = None
|
|
33
|
+
|
|
34
|
+
def routes(self) -> list[web.RouteDef]:
|
|
35
|
+
"""Return the GET route at the path of the configured redirect URI."""
|
|
36
|
+
return [web.get(URL(self.auth.redirect_uri).path, self.handle)]
|
|
37
|
+
|
|
38
|
+
def setup(self, app: web.Application) -> None:
|
|
39
|
+
"""Mount the callback on an existing application."""
|
|
40
|
+
app.add_routes(self.routes())
|
|
41
|
+
|
|
42
|
+
async def begin(self, *, scopes: Sequence[str] | None = None) -> AuthorizationAttempt:
|
|
43
|
+
"""Prepare the URL to which the application redirects its signed-in user."""
|
|
44
|
+
self.cancel()
|
|
45
|
+
self.attempt = await self.auth.begin(scopes=scopes)
|
|
46
|
+
self.outcome = asyncio.get_running_loop().create_future()
|
|
47
|
+
return self.attempt
|
|
48
|
+
|
|
49
|
+
async def wait(self) -> None:
|
|
50
|
+
"""Wait for token acquisition and persistence, or raise their error."""
|
|
51
|
+
if self.outcome is None:
|
|
52
|
+
raise RuntimeError("Start an authorization attempt first.")
|
|
53
|
+
error = await asyncio.shield(self.outcome)
|
|
54
|
+
if error is not None:
|
|
55
|
+
raise error
|
|
56
|
+
|
|
57
|
+
def cancel(self) -> None:
|
|
58
|
+
"""Cancel a pending callback without changing existing credentials."""
|
|
59
|
+
if self.attempt is not None:
|
|
60
|
+
self.auth.cancel(self.attempt)
|
|
61
|
+
self.attempt = None
|
|
62
|
+
if self.outcome is not None and not self.outcome.done():
|
|
63
|
+
self.outcome.set_result(OAuthError("Authorization was cancelled."))
|
|
64
|
+
|
|
65
|
+
async def handle(self, request: web.Request) -> web.Response:
|
|
66
|
+
"""Exchange the callback code before sending the result page."""
|
|
67
|
+
attempt, outcome = self.attempt, self.outcome
|
|
68
|
+
states = request.query.getall("state", [])
|
|
69
|
+
expected_state = URL(attempt.url).query["state"] if attempt is not None else ""
|
|
70
|
+
if (
|
|
71
|
+
attempt is None
|
|
72
|
+
or outcome is None
|
|
73
|
+
or outcome.done()
|
|
74
|
+
or len(states) != 1
|
|
75
|
+
or not hmac.compare_digest(states[0].encode(), expected_state.encode())
|
|
76
|
+
):
|
|
77
|
+
return self.response(False, "No matching authorization attempt.")
|
|
78
|
+
self.attempt = None
|
|
79
|
+
# Use the configured public URI, not an untrusted Host or Forwarded header.
|
|
80
|
+
callback_url = self.auth.redirect_uri + "?" + request.rel_url.raw_query_string
|
|
81
|
+
try:
|
|
82
|
+
await self.auth.complete(attempt, callback_url)
|
|
83
|
+
except asyncio.CancelledError:
|
|
84
|
+
if not outcome.done():
|
|
85
|
+
outcome.set_result(OAuthError("The callback request was cancelled."))
|
|
86
|
+
raise
|
|
87
|
+
except Exception as error:
|
|
88
|
+
if not outcome.done():
|
|
89
|
+
outcome.set_result(error)
|
|
90
|
+
return self.response(False, "Authorization failed. Return to the application.")
|
|
91
|
+
if outcome.done():
|
|
92
|
+
return self.response(False, "Authorization was cancelled.")
|
|
93
|
+
outcome.set_result(None)
|
|
94
|
+
return self.response(True, self.success_html)
|
|
95
|
+
|
|
96
|
+
@staticmethod
|
|
97
|
+
def response(success: bool, text: str) -> web.Response:
|
|
98
|
+
return web.Response(
|
|
99
|
+
status=200 if success else 400,
|
|
100
|
+
text=text,
|
|
101
|
+
content_type="text/html" if success else "text/plain",
|
|
102
|
+
headers={
|
|
103
|
+
"Cache-Control": "no-store",
|
|
104
|
+
"Referrer-Policy": "no-referrer",
|
|
105
|
+
"Content-Security-Policy": (
|
|
106
|
+
"default-src 'none'; style-src 'unsafe-inline'; "
|
|
107
|
+
"img-src data: https:; frame-ancestors 'none'"
|
|
108
|
+
),
|
|
109
|
+
},
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
__all__ = ["OAuthCallback", "SUCCESS_HTML"]
|
|
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
import json
|
|
6
6
|
import logging
|
|
7
7
|
from collections.abc import AsyncIterator, Callable, Mapping
|
|
8
|
+
from contextlib import asynccontextmanager
|
|
8
9
|
from typing import Any
|
|
9
10
|
|
|
10
11
|
import aiohttp
|
|
@@ -14,6 +15,7 @@ from aiohttp_tiny_mcp.protocol.models import Implementation
|
|
|
14
15
|
from aiohttp_tiny_mcp.transport.sse import read_sse
|
|
15
16
|
|
|
16
17
|
from .base import BaseClient, Elicitor
|
|
18
|
+
from .oauth import OAuth, OAuthError
|
|
17
19
|
|
|
18
20
|
ANSWER_METHOD = "elicitation/create"
|
|
19
21
|
|
|
@@ -42,6 +44,7 @@ class Client(BaseClient):
|
|
|
42
44
|
*,
|
|
43
45
|
client_info: Implementation | None = None,
|
|
44
46
|
session: aiohttp.ClientSession | None = None,
|
|
47
|
+
auth: OAuth | None = None,
|
|
45
48
|
on_ask: Elicitor | None = None,
|
|
46
49
|
on_notification: Callable[[Mapping[str, Any]], Any] | None = None,
|
|
47
50
|
log_level: str | None = None,
|
|
@@ -56,15 +59,64 @@ class Client(BaseClient):
|
|
|
56
59
|
self.base_url = base_url
|
|
57
60
|
self.session = session
|
|
58
61
|
self.owns_session = session is None
|
|
62
|
+
self.auth = auth
|
|
63
|
+
if auth is not None:
|
|
64
|
+
auth.check_endpoint(base_url)
|
|
59
65
|
#: The id of the last event read from the notification stream.
|
|
60
66
|
self.last_event_id: str | None = None
|
|
61
67
|
self.session_id: str | None = None
|
|
62
68
|
|
|
63
69
|
async def __aenter__(self) -> Client:
|
|
70
|
+
self.check_auth()
|
|
64
71
|
if self.owns_session:
|
|
65
72
|
self.session = aiohttp.ClientSession()
|
|
66
73
|
return self
|
|
67
74
|
|
|
75
|
+
def check_auth(self) -> None:
|
|
76
|
+
if self.auth is not None:
|
|
77
|
+
self.auth.check_endpoint(self.base_url)
|
|
78
|
+
if self.auth is not None and self.session is not None:
|
|
79
|
+
if "Authorization" in self.session.headers or self.session.auth is not None:
|
|
80
|
+
raise ValueError("OAuth cannot be combined with session Authorization or auth.")
|
|
81
|
+
|
|
82
|
+
@asynccontextmanager
|
|
83
|
+
async def http_request(
|
|
84
|
+
self, method: str, *, headers: dict[str, str], **kwargs: Any
|
|
85
|
+
) -> AsyncIterator[aiohttp.ClientResponse]:
|
|
86
|
+
assert self.session is not None, "use 'async with Client(...) as client:'"
|
|
87
|
+
if self.auth is None:
|
|
88
|
+
async with self.session.request(
|
|
89
|
+
method, self.base_url, headers=headers, **kwargs
|
|
90
|
+
) as resp:
|
|
91
|
+
yield resp
|
|
92
|
+
return
|
|
93
|
+
self.check_auth()
|
|
94
|
+
token = await self.auth.token()
|
|
95
|
+
for attempt in range(2):
|
|
96
|
+
async with self.session.request(
|
|
97
|
+
method,
|
|
98
|
+
self.base_url,
|
|
99
|
+
headers={**headers, "Authorization": f"Bearer {token}"},
|
|
100
|
+
allow_redirects=False,
|
|
101
|
+
**kwargs,
|
|
102
|
+
) as resp:
|
|
103
|
+
if 300 <= resp.status < 400:
|
|
104
|
+
raise OAuthError("Authenticated MCP requests must not follow redirects.")
|
|
105
|
+
if resp.status in {401, 403}:
|
|
106
|
+
challenge = self.auth.observe(resp.headers.getall("WWW-Authenticate", []))
|
|
107
|
+
if resp.status == 403:
|
|
108
|
+
if challenge.get("error") != "insufficient_scope":
|
|
109
|
+
raise OAuthError("The MCP server denied access (HTTP 403).")
|
|
110
|
+
raise self.auth.authorization_required()
|
|
111
|
+
if attempt:
|
|
112
|
+
await self.auth.invalidate(token)
|
|
113
|
+
raise self.auth.authorization_required()
|
|
114
|
+
else:
|
|
115
|
+
yield resp
|
|
116
|
+
return
|
|
117
|
+
# Release the response before refreshing, including with a one-slot connector.
|
|
118
|
+
token = await self.auth.token(rejected=token)
|
|
119
|
+
|
|
68
120
|
async def __aexit__(self, *exc: object) -> None:
|
|
69
121
|
if self.owns_session and self.session is not None:
|
|
70
122
|
await self.session.close()
|
|
@@ -100,8 +152,8 @@ class Client(BaseClient):
|
|
|
100
152
|
assert self.session is not None, "use 'async with Client(...) as client:'"
|
|
101
153
|
tool = self.tool_definitions.get(name) if name is not None else None
|
|
102
154
|
params = envelope.get("params")
|
|
103
|
-
async with self.
|
|
104
|
-
|
|
155
|
+
async with self.http_request(
|
|
156
|
+
"POST", json=envelope, headers=self.headers(method, name, params, tool)
|
|
105
157
|
) as resp:
|
|
106
158
|
if not self.lost_session(resp):
|
|
107
159
|
self.adopt(resp)
|
|
@@ -110,8 +162,8 @@ class Client(BaseClient):
|
|
|
110
162
|
return
|
|
111
163
|
# Retry once on a fresh session; a second 404 is reported as any other reply.
|
|
112
164
|
await self.reopen()
|
|
113
|
-
async with self.
|
|
114
|
-
|
|
165
|
+
async with self.http_request(
|
|
166
|
+
"POST", json=envelope, headers=self.headers(method, name, params, tool)
|
|
115
167
|
) as resp:
|
|
116
168
|
self.adopt(resp)
|
|
117
169
|
async for frame in frames(resp):
|
|
@@ -126,15 +178,15 @@ class Client(BaseClient):
|
|
|
126
178
|
async def send_notification(self, envelope: dict[str, Any], *, method: str) -> None:
|
|
127
179
|
assert self.session is not None, "use 'async with Client(...) as client:'"
|
|
128
180
|
params = envelope.get("params")
|
|
129
|
-
async with self.
|
|
130
|
-
|
|
181
|
+
async with self.http_request(
|
|
182
|
+
"POST", json=envelope, headers=self.headers(method, params=params)
|
|
131
183
|
) as resp:
|
|
132
184
|
if not self.lost_session(resp):
|
|
133
185
|
await resp.read()
|
|
134
186
|
return
|
|
135
187
|
await self.reopen()
|
|
136
|
-
async with self.
|
|
137
|
-
|
|
188
|
+
async with self.http_request(
|
|
189
|
+
"POST", json=envelope, headers=self.headers(method, params=params)
|
|
138
190
|
) as resp:
|
|
139
191
|
await resp.read()
|
|
140
192
|
|
|
@@ -147,7 +199,7 @@ class Client(BaseClient):
|
|
|
147
199
|
headers["Accept"] = "text/event-stream"
|
|
148
200
|
if last_event_id is not None:
|
|
149
201
|
headers["Last-Event-ID"] = last_event_id
|
|
150
|
-
async with self.
|
|
202
|
+
async with self.http_request("GET", headers=headers) as resp:
|
|
151
203
|
resp.raise_for_status()
|
|
152
204
|
async for event in read_sse(resp):
|
|
153
205
|
if event.id is not None:
|
|
@@ -159,5 +211,5 @@ class Client(BaseClient):
|
|
|
159
211
|
"""Send a bare JSON-RPC response. The hub routes it to the node waiting for the answer."""
|
|
160
212
|
assert self.session is not None, "use 'async with Client(...) as client:'"
|
|
161
213
|
headers = self.headers(ANSWER_METHOD)
|
|
162
|
-
async with self.
|
|
214
|
+
async with self.http_request("POST", json=envelope, headers=headers) as resp:
|
|
163
215
|
await resp.read()
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Optional browser and loopback callback helper for native applications."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import webbrowser
|
|
7
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
8
|
+
|
|
9
|
+
from aiohttp import web
|
|
10
|
+
from yarl import URL
|
|
11
|
+
|
|
12
|
+
from .callback import SUCCESS_HTML, OAuthCallback
|
|
13
|
+
from .oauth import OAuth
|
|
14
|
+
from .oauth_helpers import OAuthError
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class LoopbackCallback:
|
|
18
|
+
"""Run the aiohttp callback on 127.0.0.1 and optionally open a browser.
|
|
19
|
+
|
|
20
|
+
Enter this context before constructing OAuth, then call ``login(auth)``.
|
|
21
|
+
Register ``redirect_uri`` with the authorization server, or use DCR. A fixed
|
|
22
|
+
port can be supplied for pre-registered clients. By default, the operating
|
|
23
|
+
system selects a free port. ``success_html`` is trusted
|
|
24
|
+
application HTML, served unchanged only after the token exchange and save.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
*,
|
|
30
|
+
port: int = 0,
|
|
31
|
+
timeout: float = 300,
|
|
32
|
+
open_browser: Callable[[str], Awaitable[None]] | None = None,
|
|
33
|
+
success_html: str = SUCCESS_HTML,
|
|
34
|
+
) -> None:
|
|
35
|
+
if timeout <= 0:
|
|
36
|
+
raise ValueError("The callback timeout must be positive.")
|
|
37
|
+
self.port = port
|
|
38
|
+
self.timeout = timeout
|
|
39
|
+
self.open_browser = open_browser
|
|
40
|
+
self.success_html = success_html
|
|
41
|
+
self.runner: web.AppRunner | None = None
|
|
42
|
+
self.callback_uri: str | None = None
|
|
43
|
+
self.callback: OAuthCallback | None = None
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def redirect_uri(self) -> str:
|
|
47
|
+
if self.callback_uri is None:
|
|
48
|
+
raise RuntimeError("Enter the LoopbackCallback context first.")
|
|
49
|
+
return self.callback_uri
|
|
50
|
+
|
|
51
|
+
async def __aenter__(self) -> LoopbackCallback:
|
|
52
|
+
if self.runner is not None:
|
|
53
|
+
raise RuntimeError("The callback listener is already open.")
|
|
54
|
+
app = web.Application()
|
|
55
|
+
app.router.add_get("/callback", self.handle)
|
|
56
|
+
runner = web.AppRunner(app, access_log=None)
|
|
57
|
+
await runner.setup()
|
|
58
|
+
try:
|
|
59
|
+
await web.TCPSite(runner, "127.0.0.1", self.port).start()
|
|
60
|
+
except BaseException:
|
|
61
|
+
await runner.cleanup()
|
|
62
|
+
raise
|
|
63
|
+
self.runner = runner
|
|
64
|
+
port = runner.addresses[0][1]
|
|
65
|
+
self.callback_uri = f"http://127.0.0.1:{port}/callback"
|
|
66
|
+
return self
|
|
67
|
+
|
|
68
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
69
|
+
if self.callback is not None:
|
|
70
|
+
self.callback.cancel()
|
|
71
|
+
if self.runner is not None:
|
|
72
|
+
await self.runner.cleanup()
|
|
73
|
+
self.runner = None
|
|
74
|
+
self.callback_uri = None
|
|
75
|
+
|
|
76
|
+
async def login(self, auth: OAuth, *, scopes: Sequence[str] | None = None) -> None:
|
|
77
|
+
"""Open the browser and wait until the token exchange and save finish."""
|
|
78
|
+
if auth.redirect_uri != self.redirect_uri:
|
|
79
|
+
raise ValueError("OAuth uses another callback URI.")
|
|
80
|
+
if self.callback is not None:
|
|
81
|
+
raise RuntimeError("A browser authorization is already in progress.")
|
|
82
|
+
callback = OAuthCallback(auth, success_html=self.success_html)
|
|
83
|
+
self.callback = callback
|
|
84
|
+
try:
|
|
85
|
+
attempt = await callback.begin(scopes=scopes)
|
|
86
|
+
|
|
87
|
+
async def interact() -> None:
|
|
88
|
+
if self.open_browser is not None:
|
|
89
|
+
await self.open_browser(attempt.url)
|
|
90
|
+
elif not await asyncio.to_thread(webbrowser.open, attempt.url):
|
|
91
|
+
raise OAuthError("The browser could not be opened.")
|
|
92
|
+
await callback.wait()
|
|
93
|
+
|
|
94
|
+
await asyncio.wait_for(interact(), timeout=self.timeout)
|
|
95
|
+
finally:
|
|
96
|
+
callback.cancel()
|
|
97
|
+
self.callback = None
|
|
98
|
+
|
|
99
|
+
async def handle(self, request: web.Request) -> web.Response:
|
|
100
|
+
if request.host != URL(self.redirect_uri).authority:
|
|
101
|
+
return OAuthCallback.response(False, "Invalid callback host.")
|
|
102
|
+
if self.callback is None:
|
|
103
|
+
return OAuthCallback.response(False, "No matching authorization attempt.")
|
|
104
|
+
return await self.callback.handle(request)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
__all__ = ["LoopbackCallback"]
|