aiohttp-tiny-mcp 0.5.9__tar.gz → 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/PKG-INFO +2 -2
  2. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/README.md +1 -1
  3. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/pyproject.toml +1 -1
  4. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/pyproject.toml.orig +1 -1
  5. aiohttp_tiny_mcp-0.6.0/src/aiohttp_tiny_mcp/access_log.py +73 -0
  6. aiohttp_tiny_mcp-0.6.0/src/aiohttp_tiny_mcp/console/__init__.py +210 -0
  7. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/console/console.css +8 -0
  8. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/console/console.js +290 -38
  9. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/console/index.html +13 -7
  10. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/http.py +13 -3
  11. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/sse.py +4 -0
  12. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/sqlite.py +1 -0
  13. aiohttp_tiny_mcp-0.5.9/src/aiohttp_tiny_mcp/console/__init__.py +0 -118
  14. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/LICENSE +0 -0
  15. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/__init__.py +0 -0
  16. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/auth/__init__.py +0 -0
  17. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/auth/jwt.py +0 -0
  18. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/__init__.py +0 -0
  19. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/base.py +0 -0
  20. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/callback.py +0 -0
  21. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/http.py +0 -0
  22. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/loopback.py +0 -0
  23. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/oauth.py +0 -0
  24. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/oauth_helpers.py +0 -0
  25. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/stdio.py +0 -0
  26. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/console/oauth-callback.html +0 -0
  27. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/extensions/__init__.py +0 -0
  28. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/extensions/skills.py +0 -0
  29. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/oauth/__init__.py +0 -0
  30. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/oauth/github.py +0 -0
  31. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/oauth/provider.py +0 -0
  32. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/oauth/server.py +0 -0
  33. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/oauth/tokens.py +0 -0
  34. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/__init__.py +0 -0
  35. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/adapter.py +0 -0
  36. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/core.py +0 -0
  37. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/models.py +0 -0
  38. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/schema.py +0 -0
  39. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/selection.py +0 -0
  40. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/v2024_11_05.py +0 -0
  41. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/v2025_03_26.py +0 -0
  42. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/v2025_06_18.py +0 -0
  43. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/v2025_11_25.py +0 -0
  44. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/v2026_07_28.py +0 -0
  45. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/py.typed +0 -0
  46. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/__init__.py +0 -0
  47. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/dispatcher.py +0 -0
  48. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/exchange.py +0 -0
  49. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/registry.py +0 -0
  50. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/request_state.py +0 -0
  51. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/specs.py +0 -0
  52. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/stdio.py +0 -0
  53. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/subscriptions.py +0 -0
  54. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/tasks.py +0 -0
  55. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/__init__.py +0 -0
  56. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/hub.py +0 -0
  57. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/namespaces.py +0 -0
  58. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/postgres.py +0 -0
  59. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/redis.py +0 -0
  60. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/sessions.py +0 -0
  61. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/testing.py +0 -0
  62. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/transport/__init__.py +0 -0
  63. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/transport/metadata.py +0 -0
  64. {aiohttp_tiny_mcp-0.5.9 → aiohttp_tiny_mcp-0.6.0}/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.9
3
+ Version: 0.6.0
4
4
  Summary: Remote MCP server and client library for aiohttp
5
5
  License-Expression: Apache-2.0
6
6
  License-File: LICENSE
@@ -200,7 +200,7 @@ automatically. See [Asking the user](https://mosquito.github.io/aiohttp-tiny-mcp
200
200
 
201
201
  [MCP Chat](examples/mcp-chat/README.md) is a runnable team chat for AI agents
202
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
203
+ direct messages, threads, subscriptions, @mentions, persistent inboxes, and full-text
204
204
  search within each organization. Live MCP notifications deliver updates, with
205
205
  polling as a fallback. Optional JWT authentication binds each agent to an
206
206
  organization and user, and Observe shows its activity.
@@ -156,7 +156,7 @@ automatically. See [Asking the user](https://mosquito.github.io/aiohttp-tiny-mcp
156
156
 
157
157
  [MCP Chat](examples/mcp-chat/README.md) is a runnable team chat for AI agents
158
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
159
+ direct messages, threads, subscriptions, @mentions, persistent inboxes, and full-text
160
160
  search within each organization. Live MCP notifications deliver updates, with
161
161
  polling as a fallback. Optional JWT authentication binds each agent to an
162
162
  organization and user, and Observe shows its activity.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "aiohttp-tiny-mcp"
3
- version = "0.5.9"
3
+ version = "0.6.0"
4
4
  description = "Remote MCP server and client library for aiohttp"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "aiohttp-tiny-mcp"
3
- version = "0.5.9"
3
+ version = "0.6.0"
4
4
  description = "Remote MCP server and client library for aiohttp"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -0,0 +1,73 @@
1
+ """Aiohttp access logging without token query values."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from urllib.parse import unquote_plus
7
+
8
+ from aiohttp.log import access_logger
9
+
10
+
11
+ def mask_token(url: str) -> str:
12
+ """Mask each token query value while preserving the rest of the URL."""
13
+ path, separator, remaining = url.partition("?")
14
+ if not separator:
15
+ return url
16
+ query, fragment_separator, fragment = remaining.partition("#")
17
+ fields = []
18
+ for field in query.split("&"):
19
+ name, equals, value = field.partition("=")
20
+ if equals and unquote_plus(name).casefold() == "token":
21
+ field = f"{name}=[REDACTED]"
22
+ fields.append(field)
23
+ return path + separator + "&".join(fields) + fragment_separator + fragment
24
+
25
+
26
+ def mask_request_line(value: str) -> str:
27
+ """Mask the request target without changing the method or protocol."""
28
+ method, separator, target = value.partition(" ")
29
+ url, protocol_separator, protocol = target.rpartition(" ")
30
+ return method + separator + mask_token(url) + protocol_separator + protocol
31
+
32
+
33
+ class TokenQueryFilter(logging.Filter):
34
+ """Remove token query values from standard aiohttp access log records."""
35
+
36
+ def filter(self, record: logging.LogRecord) -> bool:
37
+ replacements: dict[str, str] = {}
38
+ request_line = getattr(record, "first_request_line", None)
39
+ if isinstance(request_line, str):
40
+ masked = mask_request_line(request_line)
41
+ if masked != request_line:
42
+ replacements[request_line] = masked
43
+ record.first_request_line = masked
44
+ for key in ("request_header", "response_header"):
45
+ headers = getattr(record, key, None)
46
+ if not isinstance(headers, dict):
47
+ continue
48
+ redacted = dict(headers)
49
+ for name, value in headers.items():
50
+ if not isinstance(value, str):
51
+ continue
52
+ masked = mask_token(value)
53
+ if masked != value:
54
+ replacements[value] = masked
55
+ redacted[name] = masked
56
+ setattr(record, key, redacted)
57
+ if replacements:
58
+ message = record.getMessage()
59
+ for value in sorted(replacements, key=len, reverse=True):
60
+ message = message.replace(value, replacements[value])
61
+ record.msg = message
62
+ record.args = ()
63
+ if hasattr(record, "message"):
64
+ record.message = message
65
+ return True
66
+
67
+
68
+ TOKEN_QUERY_FILTER = TokenQueryFilter()
69
+
70
+
71
+ def install_token_filter() -> None:
72
+ """Enable token masking once without replacing aiohttp logging configuration."""
73
+ access_logger.addFilter(TOKEN_QUERY_FILTER)
@@ -0,0 +1,210 @@
1
+ """Optional HTML console for an MCP endpoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ from collections.abc import Mapping, Sequence
8
+ from dataclasses import dataclass
9
+ from html import escape
10
+ from pathlib import Path
11
+ from typing import Any, Literal
12
+ from urllib.parse import urlsplit
13
+
14
+ from aiohttp import web
15
+ from pydantic import BaseModel
16
+
17
+ from aiohttp_tiny_mcp.protocol.schema import inline_refs
18
+
19
+ log = logging.getLogger("aiohttp_tiny_mcp")
20
+
21
+ HERE = Path(__file__).parent
22
+
23
+ FILES = {
24
+ "": ("index.html", "text/html"),
25
+ "console.js": ("console.js", "application/javascript"),
26
+ "console.css": ("console.css", "text/css"),
27
+ "oauth-callback": ("oauth-callback.html", "text/html"),
28
+ }
29
+
30
+
31
+ def check_query_property(property_schema: dict[str, Any], name: str, *, item: bool = False) -> None:
32
+ """Require one scalar type or a list of scalars, with optional nullability."""
33
+ branches = property_schema.get("anyOf", property_schema.get("oneOf"))
34
+ if branches is not None:
35
+ candidates = [branch for branch in branches if branch.get("type") != "null"]
36
+ if len(candidates) != 1:
37
+ raise ValueError(f"Query parameter {name!r} must have one non-null type.")
38
+ check_query_property(candidates[0], name, item=item)
39
+ return
40
+ kind = property_schema.get("type")
41
+ if isinstance(kind, list):
42
+ kinds = set(kind) - {"null"}
43
+ if len(kinds) > 1:
44
+ raise ValueError(f"Query parameter {name!r} must have one non-null type.")
45
+ kind = next(iter(kinds), "null")
46
+ if kind == "array" and not item:
47
+ items = property_schema.get("items", {})
48
+ check_query_property(items, name, item=True)
49
+ return
50
+ if kind not in {"string", "integer", "number", "boolean", "null"}:
51
+ raise ValueError(f"Query parameter {name!r} must be a scalar or a list of scalars.")
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class ConsoleEndpoint:
56
+ """Describe an existing MCP route and its query fields for the console."""
57
+
58
+ path: str
59
+ description: str
60
+ query: type[BaseModel] | None = None
61
+ auth: Sequence[Literal["none", "basic", "bearer", "query", "custom", "oauth"]] | None = None
62
+
63
+ def definition(self) -> dict[str, Any]:
64
+ """Return validated, JSON-compatible endpoint metadata."""
65
+ if (
66
+ not isinstance(self.path, str)
67
+ or not self.path.startswith("/")
68
+ or self.path.startswith("//")
69
+ or "\\" in self.path
70
+ or "#" in self.path
71
+ or any(ord(character) < 32 or ord(character) == 127 for character in self.path)
72
+ ):
73
+ raise ValueError("A console endpoint needs a root-relative path without a fragment.")
74
+ address = urlsplit(self.path)
75
+ if address.scheme or address.netloc:
76
+ raise ValueError("A console endpoint must be on the same origin.")
77
+ if not isinstance(self.description, str) or not self.description.strip():
78
+ raise ValueError("A console endpoint needs a nonempty description.")
79
+ auth = list(self.auth) if self.auth is not None else None
80
+ if auth is not None:
81
+ supported = {"none", "basic", "bearer", "query", "custom", "oauth"}
82
+ if not auth or any(
83
+ not isinstance(method, str) or method not in supported for method in auth
84
+ ):
85
+ raise ValueError(
86
+ "Console endpoint auth must contain supported authentication types."
87
+ )
88
+ if len(auth) != len(set(auth)):
89
+ raise ValueError("Console endpoint authentication types must be unique.")
90
+ schema: dict[str, Any] = {"type": "object", "properties": {}}
91
+ if self.query is not None:
92
+ if not isinstance(self.query, type) or not issubclass(self.query, BaseModel):
93
+ raise ValueError("A console endpoint query must be a Pydantic model class.")
94
+ try:
95
+ schema = inline_refs(self.query.model_json_schema())
96
+ except RecursionError as error:
97
+ raise ValueError("Recursive console query models are not supported.") from error
98
+ if schema.get("type") != "object" or "properties" not in schema:
99
+ raise ValueError("A console endpoint query must describe named fields.")
100
+ for name, property_schema in schema["properties"].items():
101
+ check_query_property(property_schema, name)
102
+ return {"path": self.path, "description": self.description, "query": schema, "auth": auth}
103
+
104
+
105
+ class Console:
106
+ """Serve the console."""
107
+
108
+ def __init__(
109
+ self,
110
+ endpoint_path: str = "/mcp",
111
+ *,
112
+ title: str = "MCP console",
113
+ description: str = "",
114
+ template: str | Path | None = None,
115
+ variables: Mapping[str, str] | None = None,
116
+ oauth_client_id: str | None = None,
117
+ endpoints: Sequence[ConsoleEndpoint] | None = None,
118
+ ) -> None:
119
+ self.endpoints = tuple(endpoints or ())
120
+ self.endpoint_definitions = [endpoint.definition() for endpoint in self.endpoints]
121
+ paths = [endpoint.path for endpoint in self.endpoints]
122
+ if len(paths) != len(set(paths)):
123
+ raise ValueError("Console endpoint paths must be unique.")
124
+ if not oauth_client_id and any(
125
+ "oauth" in (definition["auth"] or []) for definition in self.endpoint_definitions
126
+ ):
127
+ raise ValueError("Declared OAuth authentication requires oauth_client_id.")
128
+ self.endpoint_path = paths[0] if paths else endpoint_path
129
+ self.title = title
130
+ self.description = description
131
+ self.template = Path(template) if template else HERE / "index.html"
132
+ self.variables = dict(variables or {})
133
+ self.oauth_client_id = oauth_client_id
134
+
135
+ def substitutions(self, base: str) -> dict[str, str]:
136
+ return {
137
+ "ENDPOINT": self.endpoint_path,
138
+ "ENDPOINTS": json.dumps(self.endpoint_definitions),
139
+ "BASE": base,
140
+ "TITLE": self.title,
141
+ "DESCRIPTION": self.description,
142
+ "OAUTH_CLIENT_ID": self.oauth_client_id or "",
143
+ **self.variables,
144
+ }
145
+
146
+ def render(self, name: str, base: str = "/console") -> str:
147
+ source = self.template if name == "index.html" else HERE / name
148
+ text = source.read_text(encoding="utf-8")
149
+ for key, value in self.substitutions(base).items():
150
+ text = text.replace("{{" + key + "}}", escape(str(value), quote=True))
151
+ return text
152
+
153
+ def reached(self, request: web.Request, wanted: str) -> str:
154
+ """The prefix the browser used, taken from this request.
155
+
156
+ The page prints absolute addresses, and only the request knows them. A
157
+ subapplication adds its prefix to the request path and not to the route,
158
+ so a stored prefix would be wrong there.
159
+ """
160
+ path = request.path
161
+ if wanted:
162
+ path = path[: -(len(wanted) + 1)]
163
+ return path.rstrip("/")
164
+
165
+ async def handle(self, request: web.Request) -> web.StreamResponse:
166
+ wanted = request.match_info.get("file", "")
167
+ found = FILES.get(wanted)
168
+ if found is None:
169
+ raise web.HTTPNotFound
170
+ name, content_type = found
171
+ return web.Response(
172
+ text=self.render(name, self.reached(request, wanted)),
173
+ content_type=content_type,
174
+ charset="utf-8",
175
+ headers={"Cache-Control": "no-store"},
176
+ )
177
+
178
+ def routes(self, path: str = "/console") -> list[web.RouteDef]:
179
+ """The page, its assets, and the OAuth callback page."""
180
+ base = path.rstrip("/")
181
+ log.debug("console at %s, for the endpoint at %s", base, self.endpoint_path)
182
+ return [
183
+ web.get(base, self.handle),
184
+ web.get(f"{base}/", self.handle),
185
+ web.get(f"{base}/{{file}}", self.handle),
186
+ ]
187
+
188
+ @staticmethod
189
+ def is_public(request: web.Request) -> bool:
190
+ """Identify a mounted console asset for application authentication middleware.
191
+
192
+ Check the resolved handler, method, and file allowlist. No path prefix
193
+ is trusted, and an unmounted console grants no exemptions.
194
+ """
195
+ handler = request.match_info.handler
196
+ console = getattr(handler, "__self__", None)
197
+ return (
198
+ request.method in {"GET", "HEAD"}
199
+ and isinstance(console, Console)
200
+ and handler == console.handle
201
+ and request.match_info.get("file", "") in FILES
202
+ )
203
+
204
+ def setup(self, app: web.Application, path: str = "/console") -> web.Application:
205
+ log.debug("adding the console routes to %r", app)
206
+ app.add_routes(self.routes(path))
207
+ return app
208
+
209
+
210
+ __all__ = ["Console", "ConsoleEndpoint"]
@@ -79,6 +79,14 @@ body {
79
79
  .field.grow > input { flex: 1 1 auto; min-width: 8em; }
80
80
  .field > span { color: var(--ink-soft); font-size: 12px; }
81
81
 
82
+ .endpoint-declared { min-width: 0; }
83
+ .endpoint-declared[hidden] { display: none; }
84
+ .endpoint-declared select { width: 100%; min-width: 0; }
85
+ .endpoint-declared > p { margin: 4px 0; }
86
+ .endpoint-parameters { display: grid; gap: 12px; border: 0; margin: 0; padding: 0; min-width: 0; }
87
+ .endpoint-parameters:empty { display: none; }
88
+ .endpoint-parameters .argument { min-width: 0; margin: 0; }
89
+
82
90
  input[type="text"], input[type="password"], input[type="number"], select, textarea {
83
91
  font: inherit;
84
92
  color: inherit;
@@ -188,9 +188,19 @@ class ConsoleCredentials {
188
188
  this.endpoint = null;
189
189
  this.method = null;
190
190
  this.headers = {};
191
+ this.record = null;
191
192
  }
192
193
 
193
- set(endpoint, method, username, secret, header) {
194
+ storageKey(endpoint) {
195
+ if (typeof location === "undefined" || typeof location.pathname !== "string") return null;
196
+ return `mcp-console-credentials:${JSON.stringify([location.pathname, endpoint])}`;
197
+ }
198
+
199
+ apply(endpoint, method, username, secret, header) {
200
+ if (typeof endpoint !== "string" || !endpoint ||
201
+ ![username, secret, header].every((value) => typeof value === "string")) {
202
+ throw new Error("Enter valid authentication fields.");
203
+ }
194
204
  let name = "Authorization";
195
205
  let value;
196
206
  if (method === "basic") {
@@ -214,12 +224,45 @@ class ConsoleCredentials {
214
224
  throw new Error("The header value must use printable ASCII without surrounding spaces.");
215
225
  }
216
226
  value = secret;
217
- } else {
227
+ } else if (method !== "none" && method !== "query") {
218
228
  throw new Error("Choose an authentication method.");
219
229
  }
220
230
  this.endpoint = endpoint;
221
231
  this.method = method;
222
- this.headers = { [name]: value };
232
+ this.headers = value === undefined ? {} : { [name]: value };
233
+ this.record = { endpoint, method, username, secret, header };
234
+ }
235
+
236
+ set(endpoint, method, username, secret, header) {
237
+ this.apply(endpoint, method, username, secret, header);
238
+ try {
239
+ const key = this.storageKey(endpoint);
240
+ if (key && typeof localStorage !== "undefined") {
241
+ localStorage.setItem(key, JSON.stringify({ version: 1, ...this.record }));
242
+ }
243
+ } catch {}
244
+ }
245
+
246
+ restore(endpoint) {
247
+ this.clear();
248
+ try {
249
+ const key = this.storageKey(endpoint);
250
+ if (!key || typeof localStorage === "undefined") return false;
251
+ const record = JSON.parse(localStorage.getItem(key));
252
+ if (!record || record.version !== 1 || record.endpoint !== endpoint) return false;
253
+ this.apply(endpoint, record.method, record.username, record.secret, record.header);
254
+ return true;
255
+ } catch {
256
+ return false;
257
+ }
258
+ }
259
+
260
+ forget(endpoint) {
261
+ try {
262
+ const key = this.storageKey(endpoint);
263
+ if (key && typeof localStorage !== "undefined") localStorage.removeItem(key);
264
+ } catch {}
265
+ if (this.endpoint === endpoint) this.clear();
223
266
  }
224
267
 
225
268
  forEndpoint(endpoint) {
@@ -708,10 +751,16 @@ const page = {
708
751
  authHeaderField: document.getElementById("auth-header-field"),
709
752
  authSecret: document.getElementById("auth-secret"),
710
753
  authSecretLabel: document.getElementById("auth-secret-label"),
754
+ authSecretField: document.getElementById("auth-secret-field"),
711
755
  authError: document.getElementById("auth-error"),
712
756
  authClear: document.getElementById("auth-clear"),
713
757
  authCancel: document.getElementById("auth-cancel"),
714
758
  endpoint: document.getElementById("endpoint"),
759
+ endpointManual: document.getElementById("endpoint-manual"),
760
+ endpointDeclared: document.getElementById("endpoint-declared"),
761
+ endpointSelect: document.getElementById("endpoint-select"),
762
+ endpointDescription: document.getElementById("endpoint-description"),
763
+ endpointParameters: document.getElementById("endpoint-parameters"),
715
764
  revision: document.getElementById("revision"),
716
765
  answerable: document.getElementById("answerable"),
717
766
  notifications: document.getElementById("notifications"),
@@ -744,6 +793,8 @@ let serverInstructions = "";
744
793
  let endpointUrl = null;
745
794
  //: Where the page was told the endpoint is. The field starts from it and may add a query.
746
795
  let configuredEndpoint = null;
796
+ let endpointDeclarations = [];
797
+ let endpointFields = [];
747
798
  const credentials = new ConsoleCredentials();
748
799
  let authEndpoint = null;
749
800
  let authSchemes = [];
@@ -782,7 +833,7 @@ async function signInOAuth() {
782
833
  if (!oauthConfig) return;
783
834
  cancelOAuth?.();
784
835
  const config = oauthConfig;
785
- const endpoint = chosenEndpoint().href;
836
+ const endpoint = authenticationEndpoint().href;
786
837
  const popup = window.open("about:blank", "_blank", "popup,width=600,height=760");
787
838
  if (!popup) { page.authError.textContent = "Allow pop-up windows to sign in."; return; }
788
839
  const verifier = oauthRandom(), state = oauthRandom();
@@ -828,7 +879,9 @@ async function signInOAuth() {
828
879
  });
829
880
  const token = await exchangeOAuthCode(config, clientId, redirectUri, verifier, state, response);
830
881
  if (cancelled) throw new Error("OAuth sign-in was cancelled.");
831
- if (endpoint !== chosenEndpoint().href) throw new Error("The MCP endpoint changed during sign-in.");
882
+ if (endpoint !== authenticationEndpoint().href) throw new Error("The MCP endpoint changed during sign-in.");
883
+ const url = new URL(endpoint);
884
+ page.endpoint.value = url.pathname + url.search;
832
885
  credentials.set(endpoint, "bearer", "", token, "");
833
886
  page.authenticate.textContent = "Authentication: OAuth";
834
887
  page.authentication.close();
@@ -855,9 +908,43 @@ function authFields() {
855
908
  const method = page.authMethod.value;
856
909
  page.authUserField.hidden = method !== "basic";
857
910
  page.authHeaderField.hidden = method !== "custom";
858
- page.authSecretLabel.textContent = { basic: "Password", bearer: "Token", custom: "Header value" }[method];
911
+ page.authSecretField.hidden = !["basic", "bearer", "custom"].includes(method);
912
+ page.authSecret.required = !page.authSecretField.hidden;
913
+ page.authSecretLabel.textContent = { basic: "Password", bearer: "Token", custom: "Header value" }[method] || "Token";
859
914
  page.authSecret.value = "";
915
+ page.authSecret.edited = false;
860
916
  page.authError.textContent = "";
917
+ let url;
918
+ try { url = authenticationEndpoint(); } catch { return; }
919
+ const saved = new ConsoleCredentials();
920
+ saved.restore(url.href);
921
+ if (saved.method === method && saved.record) {
922
+ page.authUser.value = saved.record.username;
923
+ page.authHeader.value = saved.record.header || "X-API-Key";
924
+ page.authSecret.value = saved.record.secret;
925
+ }
926
+ }
927
+
928
+ function updateAuthMethods(url) {
929
+ if (url) page.authEndpoint.textContent = url.pathname + url.search;
930
+ const declaration = selectedDeclaration();
931
+ const labels = {none: "None", basic: "Basic", bearer: "Bearer token", query: "Query parameters",
932
+ custom: "Custom header", oauth: "OAuth"};
933
+ const methods = declaration?.auth || ["none", "basic", "bearer", "query", "custom"];
934
+ const previous = page.authMethod.value;
935
+ const saved = new ConsoleCredentials();
936
+ if (url) saved.restore(url.href);
937
+ page.authMethod.textContent = "";
938
+ for (const method of methods) {
939
+ const option = element("option", null, labels[method]);
940
+ option.value = method;
941
+ page.authMethod.append(option);
942
+ }
943
+ const preferred = saved.method || (url?.searchParams.has("token") ? "query" : "") ||
944
+ authSchemes.find(scheme => methods.includes(scheme)) || previous;
945
+ page.authMethod.value = methods.includes(preferred) ? preferred : methods[0];
946
+ authFields();
947
+ if (declaration?.auth && !declaration.auth.includes("oauth")) resetOAuth();
861
948
  }
862
949
 
863
950
  function openAuthentication(error) {
@@ -865,23 +952,20 @@ function openAuthentication(error) {
865
952
  try { url = chosenEndpoint(); }
866
953
  catch (failure) { say(failure.message, "off"); return; }
867
954
  if (authEndpoint !== url.href) {
868
- clearCredentials();
869
955
  resetOAuth();
870
956
  authSchemes = [];
871
957
  authEndpoint = url.href;
872
958
  }
873
959
  if (error) authSchemes = error.schemes;
874
- if (error?.resourceMetadata && error.resourceMetadata !== oauthMetadata) {
960
+ endpointDialog(url);
961
+ if (error?.resourceMetadata && error.resourceMetadata !== oauthMetadata &&
962
+ (!selectedDeclaration()?.auth || selectedDeclaration().auth.includes("oauth"))) {
875
963
  oauthMetadata = error.resourceMetadata;
876
964
  offerOAuth(oauthMetadata, url.href);
877
965
  }
878
- const offered = authSchemes.filter((scheme) => scheme === "basic" || scheme === "bearer");
879
- page.authMethod.value = credentials.method || offered[0] || (authSchemes.length ? "custom" : "basic");
880
966
  page.authMessage.textContent = authSchemes.length
881
967
  ? `Server authentication: ${authSchemes.join(", ")}.`
882
- : "Choose the method your server accepts.";
883
- page.authEndpoint.textContent = url.pathname + url.search;
884
- authFields();
968
+ : "Choose an endpoint and its authentication method.";
885
969
  if (error) page.authError.textContent = error.message;
886
970
  if (!page.authentication.open) page.authentication.showModal();
887
971
  }
@@ -890,22 +974,43 @@ function setupAuthentication() {
890
974
  page.authOAuth.onclick = signInOAuth;
891
975
  page.authenticate.onclick = () => openAuthentication();
892
976
  page.authMethod.onchange = authFields;
977
+ page.authSecret.oninput = () => { page.authSecret.edited = true; };
893
978
  page.authCancel.onclick = () => page.authentication.close();
894
979
  page.authentication.addEventListener("close", () => {
895
980
  page.authSecret.value = "";
896
981
  cancelOAuth?.();
897
982
  });
898
983
  page.authClear.onclick = () => {
984
+ let url;
985
+ try { url = authenticationEndpoint(); } catch { url = chosenEndpoint(); }
986
+ credentials.forget(url.href);
987
+ credentials.forget(chosenEndpoint().href);
988
+ for (const name of [...url.searchParams.keys()]) {
989
+ if (name.toLowerCase() === "token") url.searchParams.delete(name);
990
+ }
991
+ try { localStorage.setItem(endpointKey(), url.pathname + url.search); } catch {}
899
992
  disconnect();
900
993
  clearCredentials();
994
+ page.endpoint.value = url.pathname + url.search;
995
+ resetOAuth();
901
996
  page.authentication.close();
902
997
  };
903
998
  page.authForm.onsubmit = async (event) => {
904
999
  event.preventDefault();
905
1000
  try {
906
- const url = chosenEndpoint();
907
- credentials.set(url.href, page.authMethod.value, page.authUser.value,
908
- page.authSecret.value, page.authHeader.value);
1001
+ const url = authenticationEndpoint();
1002
+ const method = page.authMethod.value;
1003
+ if (method === "oauth" && oauthConfig) {
1004
+ await signInOAuth();
1005
+ return;
1006
+ }
1007
+ if (method === "oauth") {
1008
+ if (credentials.endpoint !== url.href) credentials.restore(url.href);
1009
+ if (credentials.method !== "bearer") credentials.apply(url.href, "none", "", "", "");
1010
+ } else {
1011
+ credentials.set(url.href, method, page.authUser.value, page.authSecret.value, page.authHeader.value);
1012
+ }
1013
+ page.endpoint.value = url.pathname + url.search;
909
1014
  page.authenticate.textContent = `Authentication: ${page.authMethod.selectedOptions[0].textContent}`;
910
1015
  page.authentication.close();
911
1016
  disconnect();
@@ -914,27 +1019,165 @@ function setupAuthentication() {
914
1019
  page.authError.textContent = error.message;
915
1020
  }
916
1021
  };
917
- page.endpoint.addEventListener("input", () => {
918
- clearCredentials();
919
- resetOAuth();
920
- authEndpoint = null;
921
- authSchemes = [];
1022
+ page.endpoint.addEventListener("input", endpointChanged);
1023
+ }
1024
+
1025
+ function endpointChanged() {
1026
+ clearCredentials();
1027
+ resetOAuth();
1028
+ authEndpoint = null;
1029
+ authSchemes = [];
1030
+ try {
1031
+ const typed = page.endpoint.value.trim();
1032
+ if (!typed) return;
1033
+ const url = new URL(typed, location.origin);
1034
+ if (url.origin === location.origin && !url.username && !url.password) {
1035
+ localStorage.setItem(endpointKey(), url.pathname + url.search);
1036
+ }
1037
+ } catch {}
1038
+ }
1039
+
1040
+ function selectedDeclaration() {
1041
+ return page.endpointSelect.value === "" ? null : endpointDeclarations[Number(page.endpointSelect.value)];
1042
+ }
1043
+
1044
+ function setupEndpoints() {
1045
+ endpointDeclarations = JSON.parse(document.documentElement.dataset.endpoints || "[]");
1046
+ if (!endpointDeclarations.length) return;
1047
+ page.endpointDeclared.hidden = false;
1048
+ const custom = element("option", null, "Custom URL");
1049
+ custom.value = "";
1050
+ page.endpointSelect.append(custom);
1051
+ endpointDeclarations.forEach((endpoint, index) => {
1052
+ const option = element("option", null, endpoint.path);
1053
+ option.value = String(index);
1054
+ page.endpointSelect.append(option);
922
1055
  });
1056
+ page.endpointSelect.onchange = () => {
1057
+ resetOAuth();
1058
+ updateDeclaredEndpoint();
1059
+ if (page.authMethod) {
1060
+ let url;
1061
+ try { url = authenticationEndpoint(); } catch {}
1062
+ updateAuthMethods(url);
1063
+ }
1064
+ };
1065
+ const changed = () => {
1066
+ resetOAuth();
1067
+ let url;
1068
+ try {
1069
+ url = authenticationEndpoint();
1070
+ page.authEndpoint.textContent = url.pathname + url.search;
1071
+ } catch {}
1072
+ if (page.authSecret && !page.authSecret.edited) authFields();
1073
+ };
1074
+ page.endpointParameters.addEventListener("input", changed);
1075
+ page.endpointParameters.addEventListener("change", changed);
1076
+ }
1077
+
1078
+ function endpointDialog(url) {
1079
+ const matches = endpointDeclarations.flatMap((item, index) => {
1080
+ const declared = new URL(item.path, location.origin);
1081
+ const fixed = [...declared.searchParams].filter(([name]) => !Object.hasOwn(item.query.properties || {}, name));
1082
+ return declared.pathname === url.pathname && fixed.every(([name, value]) => url.searchParams.getAll(name).includes(value))
1083
+ ? [{index, specificity: fixed.length}] : [];
1084
+ }).sort((first, second) => second.specificity - first.specificity);
1085
+ page.endpointSelect.value = matches.length ? String(matches[0].index) : "";
1086
+ updateDeclaredEndpoint(url);
1087
+ page.authEndpoint.textContent = url.pathname + url.search;
1088
+ updateAuthMethods(url);
1089
+ }
1090
+
1091
+ function authenticationEndpoint() {
1092
+ return selectedDeclaration() ? declaredEndpoint() : chosenEndpoint();
1093
+ }
1094
+
1095
+ function updateDeclaredEndpoint(url = null) {
1096
+ const selected = selectedDeclaration();
1097
+ page.endpointDescription.textContent = selected?.description || "Edit the endpoint URL in the main toolbar.";
1098
+ page.endpointParameters.textContent = "";
1099
+ page.endpointParameters.endpoint = url?.href || null;
1100
+ endpointFields = selected && Object.keys(selected.query.properties || {}).length
1101
+ ? buildFields(selected.query, page.endpointParameters) : [];
1102
+ for (const input of endpointFields) {
1103
+ if (input.dataset.name.toLowerCase() === "token" && input.dataset.kind === "string") {
1104
+ input.type = "password";
1105
+ input.autocomplete = "off";
1106
+ }
1107
+ const values = url?.searchParams.getAll(input.dataset.name);
1108
+ if (!values?.length) continue;
1109
+ if (input.nullToggle) {
1110
+ input.nullToggle.checked = false;
1111
+ input.nullToggle.onchange();
1112
+ }
1113
+ const kind = input.dataset.kind;
1114
+ if (kind === "boolean") input.checked = values[0] === "true" || values[0] === "1";
1115
+ else if (kind === "choice") {
1116
+ const option = [...input.options].find(option => option.value && String(JSON.parse(option.value)) === values[0]);
1117
+ if (option) input.value = option.value;
1118
+ } else if (kind === "choices") {
1119
+ for (const option of input.choiceInputs) option.checked = values.includes(String(JSON.parse(option.value)));
1120
+ } else if (kind === "array") {
1121
+ const property = selected.query.properties[input.dataset.name];
1122
+ const schema = property.items ? property : (property.anyOf || []).find(branch => branch.items);
1123
+ const itemType = schema?.items.type;
1124
+ const converted = values.map(value => ["number", "integer"].includes(itemType) ? Number(value)
1125
+ : itemType === "boolean" ? value === "true" : value);
1126
+ input.value = JSON.stringify(converted);
1127
+ } else input.value = values[0];
1128
+ }
1129
+ }
1130
+
1131
+ function setEndpointDisabled(disabled) {
1132
+ page.endpoint.disabled = disabled;
1133
+ }
1134
+
1135
+ function declaredEndpoint() {
1136
+ const selected = selectedDeclaration();
1137
+ if (!selected) throw new Error("Choose an MCP endpoint.");
1138
+ const url = new URL(page.endpointParameters.endpoint || selected.path, location.origin);
1139
+ if (url.origin !== location.origin || url.username || url.password || url.hash) {
1140
+ throw new Error("The endpoint must be a path on this server.");
1141
+ }
1142
+ const absent = missing(endpointFields);
1143
+ if (absent.length) throw new Error(`Fill in query parameters: ${absent.map(input => input.dataset.name).join(", ")}.`);
1144
+ const values = readFields(endpointFields);
1145
+ for (const input of endpointFields) {
1146
+ if (input.dataset.kind === "string" && values[input.dataset.name] !== undefined && values[input.dataset.name] !== null) {
1147
+ values[input.dataset.name] = input.value;
1148
+ }
1149
+ }
1150
+ for (const name of selected.query.required || []) {
1151
+ if (values[name] === null || values[name] === undefined || (Array.isArray(values[name]) && !values[name].length)) {
1152
+ throw new Error(`Fill in query parameter: ${name}.`);
1153
+ }
1154
+ }
1155
+ for (const name of Object.keys(selected.query.properties || {})) {
1156
+ url.searchParams.delete(name);
1157
+ }
1158
+ for (const [name, value] of Object.entries(values)) {
1159
+ for (const item of Array.isArray(value) ? value : [value]) {
1160
+ if (item === null) continue;
1161
+ if (!["string", "boolean", "number"].includes(typeof item) || (typeof item === "number" && !Number.isFinite(item))) {
1162
+ throw new Error(`${name}: query parameters must contain scalar values.`);
1163
+ }
1164
+ url.searchParams.append(name, String(item));
1165
+ }
1166
+ }
1167
+ return url;
923
1168
  }
924
1169
 
925
- // The endpoint field: the path, plus any query string a person adds, such as
926
- // `?mcp=2025-06-18` to pin a revision or whatever the server reads from the URL.
927
- // The value is kept for the next visit while its path is still the configured one,
928
- // so a server moved elsewhere is not chased at a stale address.
929
1170
  function endpointKey() {
930
1171
  return `mcp-console-endpoint:${location.pathname}`;
931
1172
  }
932
1173
 
933
1174
  function rememberedEndpoint() {
934
- const kept = localStorage.getItem(endpointKey());
935
- if (!kept) return null;
936
- const url = new URL(kept, location.origin);
937
- return url.pathname === configuredEndpoint.pathname ? kept : null;
1175
+ try {
1176
+ const kept = localStorage.getItem(endpointKey());
1177
+ if (!kept) return null;
1178
+ const url = new URL(kept, location.origin);
1179
+ return url.origin === location.origin && !url.username && !url.password ? kept : null;
1180
+ } catch { return null; }
938
1181
  }
939
1182
 
940
1183
  function chosenEndpoint() {
@@ -946,7 +1189,7 @@ function chosenEndpoint() {
946
1189
  if (url.username || url.password) throw new Error("Enter credentials through Authentication.");
947
1190
  url.hash = "";
948
1191
  page.endpoint.value = url.pathname + url.search;
949
- localStorage.setItem(endpointKey(), page.endpoint.value);
1192
+ try { localStorage.setItem(endpointKey(), page.endpoint.value); } catch {}
950
1193
  return url;
951
1194
  }
952
1195
 
@@ -2051,7 +2294,7 @@ function disconnect() {
2051
2294
  page.revision.disabled = false;
2052
2295
  page.answerable.disabled = false;
2053
2296
  page.notifications.disabled = false;
2054
- page.endpoint.disabled = false;
2297
+ setEndpointDisabled(false);
2055
2298
  page.connect.textContent = "Connect";
2056
2299
  say("not connected", "");
2057
2300
  }
@@ -2062,12 +2305,13 @@ async function connect() {
2062
2305
  page.revision.disabled = true;
2063
2306
  page.answerable.disabled = true;
2064
2307
  page.notifications.disabled = true;
2065
- page.endpoint.disabled = true;
2308
+ setEndpointDisabled(true);
2066
2309
  say("connecting", "");
2067
2310
  page.outcome.textContent = "";
2068
2311
  try {
2069
2312
  endpointUrl = chosenEndpoint();
2070
- if (credentials.endpoint && credentials.endpoint !== endpointUrl.href) clearCredentials();
2313
+ if (credentials.endpoint !== endpointUrl.href) credentials.restore(endpointUrl.href);
2314
+ page.authenticate.textContent = credentials.method ? `Authentication: ${credentials.method}` : "Authentication";
2071
2315
  client = new Client(endpointUrl.href, page.revision.value, {
2072
2316
  authHeaders: credentials.forEndpoint(endpointUrl.href),
2073
2317
  onAuthError: openAuthentication,
@@ -2095,7 +2339,7 @@ async function connect() {
2095
2339
  page.revision.disabled = false;
2096
2340
  page.answerable.disabled = false;
2097
2341
  page.notifications.disabled = false;
2098
- page.endpoint.disabled = false;
2342
+ setEndpointDisabled(false);
2099
2343
  page.connect.textContent = "Connect";
2100
2344
  say(error.message, "off");
2101
2345
  report("Could not connect", connectionHelp(error), true);
@@ -2175,11 +2419,21 @@ function start() {
2175
2419
  option.value = version;
2176
2420
  page.revision.append(option);
2177
2421
  });
2178
- const remembered = localStorage.getItem("mcp-console-revision");
2422
+ let remembered;
2423
+ try { remembered = localStorage.getItem("mcp-console-revision"); } catch {}
2179
2424
  page.revision.value = REVISIONS[remembered] ? remembered : Object.keys(REVISIONS)[0];
2180
2425
 
2181
2426
  configuredEndpoint = new URL(document.documentElement.dataset.endpoint || "/mcp", location.origin);
2427
+ setupEndpoints();
2182
2428
  page.endpoint.value = rememberedEndpoint() || configuredEndpoint.pathname + configuredEndpoint.search;
2429
+ if (!rememberedEndpoint() && endpointDeclarations.length) {
2430
+ page.endpointSelect.value = "0";
2431
+ updateDeclaredEndpoint();
2432
+ try {
2433
+ const url = declaredEndpoint();
2434
+ page.endpoint.value = url.pathname + url.search;
2435
+ } catch {}
2436
+ }
2183
2437
  page.endpoint.onkeydown = (event) => {
2184
2438
  if (event.key === "Enter" && !client) {
2185
2439
  event.preventDefault();
@@ -2214,10 +2468,8 @@ function start() {
2214
2468
  page.traffic.append(element("p", "empty", "Every message, as it goes over the wire."));
2215
2469
  };
2216
2470
  page.revision.onchange = () => {
2217
- localStorage.setItem("mcp-console-revision", page.revision.value);
2471
+ try { localStorage.setItem("mcp-console-revision", page.revision.value); } catch {}
2218
2472
  };
2219
-
2220
- connect();
2221
2473
  }
2222
2474
 
2223
2475
  if (document.documentElement.dataset.oauthCallback === "true") {
@@ -1,5 +1,5 @@
1
1
  <!doctype html>
2
- <html lang="en" data-endpoint="{{ENDPOINT}}" data-console="{{BASE}}" data-oauth-client-id="{{OAUTH_CLIENT_ID}}">
2
+ <html lang="en" data-endpoint="{{ENDPOINT}}" data-endpoints="{{ENDPOINTS}}" data-console="{{BASE}}" data-oauth-client-id="{{OAUTH_CLIENT_ID}}">
3
3
  <head>
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -11,7 +11,7 @@
11
11
 
12
12
  <header class="bar">
13
13
  <h1><button id="server-title" type="button" title="Show server instructions" disabled>{{TITLE}}</button></h1>
14
- <label class="field grow" title="The path the server serves MCP on. A query string is sent as typed">
14
+ <label id="endpoint-manual" class="field grow" title="The path the server serves MCP on. A query string is sent as typed">
15
15
  <span>Endpoint</span>
16
16
  <input id="endpoint" class="endpoint" type="text" spellcheck="false" autocomplete="off">
17
17
  </label>
@@ -105,8 +105,12 @@
105
105
  <h2 id="auth-title">Authentication</h2>
106
106
  <p id="auth-message">Enter credentials for this endpoint.</p>
107
107
  <p id="auth-endpoint" class="auth-endpoint"></p>
108
- <button id="auth-oauth" class="primary" type="button" hidden>Sign in with OAuth</button>
109
- <p id="auth-oauth-status" class="auth-help" role="status"></p>
108
+ <section id="endpoint-declared" class="endpoint-declared" hidden aria-label="MCP endpoint">
109
+ <label class="auth-field" for="endpoint-select"><span>Endpoint</span>
110
+ <select id="endpoint-select" class="endpoint" aria-describedby="endpoint-description"></select>
111
+ </label>
112
+ <p id="endpoint-description" class="hint"></p>
113
+ </section>
110
114
  <label class="auth-field">Method
111
115
  <select id="auth-method">
112
116
  <option value="basic">Basic</option>
@@ -114,17 +118,19 @@
114
118
  <option value="custom">Custom header</option>
115
119
  </select>
116
120
  </label>
121
+ <button id="auth-oauth" class="primary" type="button" hidden>Sign in with OAuth</button>
122
+ <p id="auth-oauth-status" class="auth-help" role="status"></p>
117
123
  <label id="auth-user-field" class="auth-field">Username
118
124
  <input id="auth-user" type="text" autocomplete="off" spellcheck="false">
119
125
  </label>
120
126
  <label id="auth-header-field" class="auth-field" hidden>Header name
121
127
  <input id="auth-header" type="text" value="X-API-Key" autocomplete="off" spellcheck="false">
122
128
  </label>
123
- <label class="auth-field"><span id="auth-secret-label">Password</span>
129
+ <label id="auth-secret-field" class="auth-field"><span id="auth-secret-label">Password</span>
124
130
  <input id="auth-secret" type="password" autocomplete="off" required>
125
131
  </label>
126
- <p class="auth-help">Credentials stay in this page's memory until you clear them or reload.
127
- Enter an existing Bearer token or use configured OAuth sign-in.</p>
132
+ <fieldset id="endpoint-parameters" class="endpoint-parameters" aria-label="Query parameters"></fieldset>
133
+ <p class="auth-help">Credentials are saved in this browser. Clear removes saved credentials for this endpoint.</p>
128
134
  <p id="auth-error" class="auth-error" role="alert"></p>
129
135
  <menu>
130
136
  <button id="auth-clear" class="quiet" type="button">Clear</button>
@@ -13,6 +13,7 @@ from typing import Any
13
13
 
14
14
  from aiohttp import web
15
15
 
16
+ from aiohttp_tiny_mcp.access_log import install_token_filter
16
17
  from aiohttp_tiny_mcp.auth import Authentication, Principal, Unauthorized
17
18
  from aiohttp_tiny_mcp.protocol.adapter import Adapter
18
19
  from aiohttp_tiny_mcp.protocol.core import (
@@ -220,15 +221,24 @@ class Endpoint:
220
221
  )
221
222
 
222
223
  def setup(
223
- self, app: web.Application, path: str = "/mcp", *, name: str | None = "mcp"
224
+ self,
225
+ app: web.Application,
226
+ path: str = "/mcp",
227
+ *,
228
+ name: str | None = "mcp",
229
+ mask_tokens_in_logs: bool = True,
224
230
  ) -> web.Application:
231
+ if mask_tokens_in_logs:
232
+ install_token_filter()
225
233
  log.debug("adding the MCP routes to %r", app)
226
234
  app[MCP_ENDPOINT] = self
227
235
  app.add_routes(self.routes(path, name=name))
228
236
  return app
229
237
 
230
- def app(self, path: str = "/mcp", **kw: Any) -> web.Application:
231
- return self.setup(web.Application(**kw), path)
238
+ def app(
239
+ self, path: str = "/mcp", *, mask_tokens_in_logs: bool = True, **kw: Any
240
+ ) -> web.Application:
241
+ return self.setup(web.Application(**kw), path, mask_tokens_in_logs=mask_tokens_in_logs)
232
242
 
233
243
  def check_origin(self, request: web.Request) -> None:
234
244
  origin = request.headers.get("Origin")
@@ -11,6 +11,7 @@ from typing import Any
11
11
 
12
12
  from aiohttp import web
13
13
 
14
+ from aiohttp_tiny_mcp.access_log import install_token_filter
14
15
  from aiohttp_tiny_mcp.auth import Principal, Unauthorized
15
16
  from aiohttp_tiny_mcp.protocol.adapter import Adapter
16
17
  from aiohttp_tiny_mcp.protocol.core import (
@@ -326,7 +327,10 @@ class SseEndpoint:
326
327
  message_path: str | None = None,
327
328
  *,
328
329
  metadata: bool = True,
330
+ mask_tokens_in_logs: bool = True,
329
331
  ) -> web.Application:
332
+ if mask_tokens_in_logs:
333
+ install_token_filter()
330
334
  log.debug("adding the HTTP+SSE routes to %r", app)
331
335
  app.add_routes(self.routes(sse_path, message_path, metadata=metadata))
332
336
  return app
@@ -38,6 +38,7 @@ CREATE TABLE IF NOT EXISTS mcp_events (
38
38
  created_at INTEGER NOT NULL
39
39
  );
40
40
  CREATE INDEX IF NOT EXISTS mcp_events_topic ON mcp_events (topic, id);
41
+ CREATE INDEX IF NOT EXISTS mcp_events_expiry ON mcp_events (created_at);
41
42
  """
42
43
 
43
44
  NOW = "CAST(strftime('%s', 'now') AS INTEGER)"
@@ -1,118 +0,0 @@
1
- """Optional HTML console for an MCP endpoint."""
2
-
3
- from __future__ import annotations
4
-
5
- import logging
6
- from collections.abc import Mapping
7
- from html import escape
8
- from pathlib import Path
9
-
10
- from aiohttp import web
11
-
12
- log = logging.getLogger("aiohttp_tiny_mcp")
13
-
14
- HERE = Path(__file__).parent
15
-
16
- FILES = {
17
- "": ("index.html", "text/html"),
18
- "console.js": ("console.js", "application/javascript"),
19
- "console.css": ("console.css", "text/css"),
20
- "oauth-callback": ("oauth-callback.html", "text/html"),
21
- }
22
-
23
-
24
- class Console:
25
- """Serve the console."""
26
-
27
- def __init__(
28
- self,
29
- endpoint_path: str = "/mcp",
30
- *,
31
- title: str = "MCP console",
32
- description: str = "",
33
- template: str | Path | None = None,
34
- variables: Mapping[str, str] | None = None,
35
- oauth_client_id: str | None = None,
36
- ) -> None:
37
- self.endpoint_path = endpoint_path
38
- self.title = title
39
- self.description = description
40
- self.template = Path(template) if template else HERE / "index.html"
41
- self.variables = dict(variables or {})
42
- self.oauth_client_id = oauth_client_id
43
-
44
- def substitutions(self, base: str) -> dict[str, str]:
45
- return {
46
- "ENDPOINT": self.endpoint_path,
47
- "BASE": base,
48
- "TITLE": self.title,
49
- "DESCRIPTION": self.description,
50
- "OAUTH_CLIENT_ID": self.oauth_client_id or "",
51
- **self.variables,
52
- }
53
-
54
- def render(self, name: str, base: str = "/console") -> str:
55
- source = self.template if name == "index.html" else HERE / name
56
- text = source.read_text(encoding="utf-8")
57
- for key, value in self.substitutions(base).items():
58
- text = text.replace("{{" + key + "}}", escape(str(value), quote=True))
59
- return text
60
-
61
- def reached(self, request: web.Request, wanted: str) -> str:
62
- """The prefix the browser used, taken from this request.
63
-
64
- The page prints absolute addresses, and only the request knows them. A
65
- subapplication adds its prefix to the request path and not to the route,
66
- so a stored prefix would be wrong there.
67
- """
68
- path = request.path
69
- if wanted:
70
- path = path[: -(len(wanted) + 1)]
71
- return path.rstrip("/")
72
-
73
- async def handle(self, request: web.Request) -> web.StreamResponse:
74
- wanted = request.match_info.get("file", "")
75
- found = FILES.get(wanted)
76
- if found is None:
77
- raise web.HTTPNotFound
78
- name, content_type = found
79
- return web.Response(
80
- text=self.render(name, self.reached(request, wanted)),
81
- content_type=content_type,
82
- charset="utf-8",
83
- headers={"Cache-Control": "no-store"},
84
- )
85
-
86
- def routes(self, path: str = "/console") -> list[web.RouteDef]:
87
- """The page, its assets, and the OAuth callback page."""
88
- base = path.rstrip("/")
89
- log.debug("console at %s, for the endpoint at %s", base, self.endpoint_path)
90
- return [
91
- web.get(base, self.handle),
92
- web.get(f"{base}/", self.handle),
93
- web.get(f"{base}/{{file}}", self.handle),
94
- ]
95
-
96
- @staticmethod
97
- def is_public(request: web.Request) -> bool:
98
- """Identify a mounted console asset for application authentication middleware.
99
-
100
- Check the resolved handler, method, and file allowlist. No path prefix
101
- is trusted, and an unmounted console grants no exemptions.
102
- """
103
- handler = request.match_info.handler
104
- console = getattr(handler, "__self__", None)
105
- return (
106
- request.method in {"GET", "HEAD"}
107
- and isinstance(console, Console)
108
- and handler == console.handle
109
- and request.match_info.get("file", "") in FILES
110
- )
111
-
112
- def setup(self, app: web.Application, path: str = "/console") -> web.Application:
113
- log.debug("adding the console routes to %r", app)
114
- app.add_routes(self.routes(path))
115
- return app
116
-
117
-
118
- __all__ = ["Console"]