aiohttp-tiny-mcp 0.5.8__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.8 → aiohttp_tiny_mcp-0.6.0}/PKG-INFO +19 -1
  2. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/README.md +18 -0
  3. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/pyproject.toml +5 -2
  4. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/pyproject.toml.orig +2 -2
  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.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/console/console.css +8 -0
  8. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/console/console.js +478 -65
  9. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/console/index.html +17 -7
  10. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/http.py +13 -3
  11. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/sse.py +4 -0
  12. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/sqlite.py +63 -33
  13. aiohttp_tiny_mcp-0.5.8/src/aiohttp_tiny_mcp/console/__init__.py +0 -118
  14. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/LICENSE +0 -0
  15. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/__init__.py +0 -0
  16. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/auth/__init__.py +0 -0
  17. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/auth/jwt.py +0 -0
  18. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/__init__.py +0 -0
  19. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/base.py +0 -0
  20. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/callback.py +0 -0
  21. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/http.py +0 -0
  22. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/loopback.py +0 -0
  23. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/oauth.py +0 -0
  24. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/oauth_helpers.py +0 -0
  25. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/client/stdio.py +0 -0
  26. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/console/oauth-callback.html +0 -0
  27. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/extensions/__init__.py +0 -0
  28. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/extensions/skills.py +0 -0
  29. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/oauth/__init__.py +0 -0
  30. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/oauth/github.py +0 -0
  31. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/oauth/provider.py +0 -0
  32. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/oauth/server.py +0 -0
  33. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/oauth/tokens.py +0 -0
  34. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/__init__.py +0 -0
  35. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/adapter.py +0 -0
  36. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/core.py +0 -0
  37. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/models.py +0 -0
  38. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/schema.py +0 -0
  39. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/selection.py +0 -0
  40. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/v2024_11_05.py +0 -0
  41. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/v2025_03_26.py +0 -0
  42. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/v2025_06_18.py +0 -0
  43. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/v2025_11_25.py +0 -0
  44. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/protocol/v2026_07_28.py +0 -0
  45. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/py.typed +0 -0
  46. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/__init__.py +0 -0
  47. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/dispatcher.py +0 -0
  48. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/exchange.py +0 -0
  49. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/registry.py +0 -0
  50. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/request_state.py +0 -0
  51. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/specs.py +0 -0
  52. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/stdio.py +0 -0
  53. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/subscriptions.py +0 -0
  54. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/server/tasks.py +0 -0
  55. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/__init__.py +0 -0
  56. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/hub.py +0 -0
  57. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/namespaces.py +0 -0
  58. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/postgres.py +0 -0
  59. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/redis.py +0 -0
  60. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/storage/sessions.py +0 -0
  61. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/testing.py +0 -0
  62. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/transport/__init__.py +0 -0
  63. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.6.0}/src/aiohttp_tiny_mcp/transport/metadata.py +0 -0
  64. {aiohttp_tiny_mcp-0.5.8 → 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.8
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
@@ -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, @mentions, 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, @mentions, 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.8"
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"
@@ -116,7 +116,10 @@ root = [
116
116
  ]
117
117
 
118
118
  [tool.ty.src]
119
- exclude = ["examples/docker-mcp"]
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.8"
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"
@@ -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"]
@@ -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;