aiohttp-tiny-mcp 0.6.0__tar.gz → 0.7.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 (65) hide show
  1. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/PKG-INFO +1 -1
  2. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/pyproject.toml +1 -1
  3. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/pyproject.toml.orig +1 -1
  4. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/console/__init__.py +1 -0
  5. aiohttp_tiny_mcp-0.7.0/src/aiohttp_tiny_mcp/console/agent-config.js +111 -0
  6. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/console/console.css +30 -4
  7. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/console/console.js +178 -5
  8. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/console/index.html +41 -0
  9. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/protocol/adapter.py +1 -0
  10. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/protocol/core.py +1 -0
  11. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/server/dispatcher.py +21 -11
  12. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/server/http.py +16 -2
  13. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/server/registry.py +10 -0
  14. aiohttp_tiny_mcp-0.7.0/src/aiohttp_tiny_mcp/server/resource_auth.py +68 -0
  15. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/server/specs.py +7 -0
  16. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/server/sse.py +14 -2
  17. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/server/subscriptions.py +7 -1
  18. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/LICENSE +0 -0
  19. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/README.md +0 -0
  20. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/__init__.py +0 -0
  21. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/access_log.py +0 -0
  22. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/auth/__init__.py +0 -0
  23. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/auth/jwt.py +0 -0
  24. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/client/__init__.py +0 -0
  25. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/client/base.py +0 -0
  26. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/client/callback.py +0 -0
  27. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/client/http.py +0 -0
  28. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/client/loopback.py +0 -0
  29. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/client/oauth.py +0 -0
  30. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/client/oauth_helpers.py +0 -0
  31. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/client/stdio.py +0 -0
  32. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/console/oauth-callback.html +0 -0
  33. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/extensions/__init__.py +0 -0
  34. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/extensions/skills.py +0 -0
  35. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/oauth/__init__.py +0 -0
  36. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/oauth/github.py +0 -0
  37. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/oauth/provider.py +0 -0
  38. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/oauth/server.py +0 -0
  39. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/oauth/tokens.py +0 -0
  40. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/protocol/__init__.py +0 -0
  41. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/protocol/models.py +0 -0
  42. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/protocol/schema.py +0 -0
  43. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/protocol/selection.py +0 -0
  44. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/protocol/v2024_11_05.py +0 -0
  45. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/protocol/v2025_03_26.py +0 -0
  46. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/protocol/v2025_06_18.py +0 -0
  47. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/protocol/v2025_11_25.py +0 -0
  48. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/protocol/v2026_07_28.py +0 -0
  49. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/py.typed +0 -0
  50. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/server/__init__.py +0 -0
  51. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/server/exchange.py +0 -0
  52. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/server/request_state.py +0 -0
  53. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/server/stdio.py +0 -0
  54. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/server/tasks.py +0 -0
  55. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/storage/__init__.py +0 -0
  56. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/storage/hub.py +0 -0
  57. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/storage/namespaces.py +0 -0
  58. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/storage/postgres.py +0 -0
  59. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/storage/redis.py +0 -0
  60. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/storage/sessions.py +0 -0
  61. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/storage/sqlite.py +0 -0
  62. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/testing.py +0 -0
  63. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/transport/__init__.py +0 -0
  64. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.0}/src/aiohttp_tiny_mcp/transport/metadata.py +0 -0
  65. {aiohttp_tiny_mcp-0.6.0 → aiohttp_tiny_mcp-0.7.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.6.0
3
+ Version: 0.7.0
4
4
  Summary: Remote MCP server and client library for aiohttp
5
5
  License-Expression: Apache-2.0
6
6
  License-File: LICENSE
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "aiohttp-tiny-mcp"
3
- version = "0.6.0"
3
+ version = "0.7.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.6.0"
3
+ version = "0.7.0"
4
4
  description = "Remote MCP server and client library for aiohttp"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -23,6 +23,7 @@ HERE = Path(__file__).parent
23
23
  FILES = {
24
24
  "": ("index.html", "text/html"),
25
25
  "console.js": ("console.js", "application/javascript"),
26
+ "agent-config.js": ("agent-config.js", "application/javascript"),
26
27
  "console.css": ("console.css", "text/css"),
27
28
  "oauth-callback": ("oauth-callback.html", "text/html"),
28
29
  }
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+
3
+ function agentConfigurations({endpoint, name = 'mcp', headers = {}, level = 'user'} = {}) {
4
+ if (!['project', 'user'].includes(level)) {
5
+ throw new Error('Choose Project or User configuration level.');
6
+ }
7
+ if (typeof name !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(name)) {
8
+ throw new Error('Use 1–64 letters, numbers, underscores, or hyphens for the server name.');
9
+ }
10
+ const controls = /[\x00-\x1f\x7f]/;
11
+ const loneSurrogate = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/;
12
+ if (typeof endpoint !== 'string' || controls.test(endpoint) || loneSurrogate.test(endpoint)
13
+ || endpoint !== endpoint.trim() || !/^https?:\/\//i.test(endpoint)) {
14
+ throw new Error('Enter an absolute HTTP or HTTPS endpoint URL.');
15
+ }
16
+ let url;
17
+ try {
18
+ url = new URL(endpoint);
19
+ } catch {
20
+ throw new Error('Enter a valid endpoint URL.');
21
+ }
22
+ if (url.username || url.password || endpoint.includes('#')) {
23
+ throw new Error('The endpoint URL must not contain credentials or a fragment.');
24
+ }
25
+ if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
26
+ throw new Error('Headers must be an object.');
27
+ }
28
+ const entries = Object.entries(headers);
29
+ for (const [key, value] of entries) {
30
+ if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(key)
31
+ || typeof value !== 'string' || controls.test(value) || loneSurrogate.test(value)) {
32
+ throw new Error('Use valid HTTP header names and values without control characters.');
33
+ }
34
+ }
35
+ const credentials = entries.length ? {headers: Object.fromEntries(entries)} : {};
36
+ const server = {url: endpoint, ...credentials};
37
+ const json = value => JSON.stringify(value, null, 2);
38
+ const named = value => ({mcpServers: {[name]: value}});
39
+ const merge = 'Create the file if it does not exist. Merge this server entry with existing settings.';
40
+ const userLevel = level === 'user';
41
+ const file = (projectPath, userPath) => {
42
+ const target = userLevel ? userPath : projectPath;
43
+ const location = userLevel ? 'your home directory for all your projects' : 'your project root';
44
+ return {target, instructions: `Add the configuration below to ${target} in ${location}. ${merge}`};
45
+ };
46
+ const signIn = entries.length || url.searchParams.has('token')
47
+ ? '' : ' If the server requires OAuth, sign in from the agent.';
48
+ const tomlHeaders = entries.length
49
+ ? '\nhttp_headers = { ' + entries.map(([key, value]) =>
50
+ `${JSON.stringify(key)} = ${JSON.stringify(value)}`).join(', ') + ' }' : '';
51
+ const remote = {type: 'remote', ...server};
52
+ if (entries.length || url.searchParams.has('token')) remote.oauth = false;
53
+ return [
54
+ {
55
+ id: 'mcp-json', label: 'Claude Code',
56
+ ...file('.mcp.json', '~/.claude.json'),
57
+ code: json(named({type: 'http', ...server})), language: 'json',
58
+ verify: (userLevel ? 'Start Claude Code and open /mcp.'
59
+ : 'Start Claude Code in this project, approve the server, and open /mcp.') + signIn,
60
+ link: `https://code.claude.com/docs/en/mcp#${level}-scope`,
61
+ },
62
+ {
63
+ id: 'codex', label: 'Codex',
64
+ ...file('.codex/config.toml', '~/.codex/config.toml'),
65
+ code: `[mcp_servers.${JSON.stringify(name)}]\nurl = ${JSON.stringify(endpoint)}${tomlHeaders}\n`,
66
+ language: 'toml',
67
+ verify: (userLevel ? '' : 'Trust this project in Codex first. ')
68
+ + 'Run codex mcp list to check the server.'
69
+ + (signIn ? ` For OAuth, run codex mcp login ${name}.` : ''),
70
+ link: 'https://learn.chatgpt.com/docs/extend/mcp?surface=cli',
71
+ },
72
+ {
73
+ id: 'cursor', label: 'Cursor',
74
+ ...file('.cursor/mcp.json', '~/.cursor/mcp.json'),
75
+ code: json(named(server)), language: 'json',
76
+ verify: 'Open Cursor Settings → Tools & MCP and check the server.' + signIn,
77
+ link: 'https://cursor.com/docs/mcp',
78
+ },
79
+ {
80
+ id: 'copilot', label: 'GitHub Copilot',
81
+ ...file('.mcp.json', '~/.copilot/mcp-config.json'),
82
+ code: json(named({type: 'http', ...server, tools: ['*']})), language: 'json',
83
+ verify: 'In VS Code, run MCP: List Servers and start the server.' + signIn,
84
+ link: 'https://code.visualstudio.com/docs/agents/reference/mcp-configuration',
85
+ },
86
+ {
87
+ id: 'gemini', label: 'Gemini CLI',
88
+ ...file('.gemini/settings.json', '~/.gemini/settings.json'),
89
+ code: json(named({httpUrl: endpoint, ...credentials})), language: 'json',
90
+ verify: (userLevel ? 'Start Gemini CLI and open /mcp.'
91
+ : 'Start Gemini CLI in this project and open /mcp.') + signIn,
92
+ link: 'https://geminicli.com/docs/tools/mcp-server/',
93
+ },
94
+ {
95
+ id: 'pi', label: 'Pi',
96
+ ...file('.pi/mcp.json', '~/.pi/agent/mcp.json'),
97
+ code: json(named(server)), language: 'json',
98
+ verify: (userLevel ? 'Start Pi and open /mcp.'
99
+ : 'Trust this project in Pi, then open /mcp.') + signIn,
100
+ link: 'https://docs.pi.dev/latest/mcp',
101
+ },
102
+ {
103
+ id: 'opencode', label: 'OpenCode V2',
104
+ ...file('opencode.json', '~/.config/opencode/opencode.json'),
105
+ code: json({$schema: 'https://opencode.ai/config.json', mcp: {servers: {[name]: remote}}}),
106
+ language: 'json',
107
+ verify: 'Run opencode mcp list to check the server.' + signIn,
108
+ link: 'https://opencode.ai/docs/mcp-servers/',
109
+ },
110
+ ];
111
+ }
@@ -300,12 +300,21 @@ button.quiet { color: var(--ink-soft); }
300
300
  .about > :first-child { margin-top: 0; }
301
301
  .about > :last-child { margin-bottom: 0; }
302
302
  .about p { margin: 0 0 8px; }
303
- .about h3, .about h4, .about h5, .about h6 {
303
+ :is(.about, #question-text) :is(h1, h2, h3, h4, h5, h6, [role="heading"]) {
304
304
  color: var(--ink);
305
- font-size: 13px;
306
305
  font-weight: 600;
307
- margin: 14px 0 6px;
306
+ line-height: 1.3;
307
+ margin: 1.2em 0 0.45em;
308
+ overflow-wrap: anywhere;
308
309
  }
310
+ :is(.about, #question-text) h1 { font-size: 1.8em; }
311
+ :is(.about, #question-text) h2 { font-size: 1.55em; }
312
+ :is(.about, #question-text) h3 { font-size: 1.35em; }
313
+ :is(.about, #question-text) h4 { font-size: 1.2em; }
314
+ :is(.about, #question-text) h5 { font-size: 1.1em; }
315
+ :is(.about, #question-text) h6 { font-size: 1em; }
316
+ :is(.about, #question-text) [role="heading"][aria-level="7"] { font-size: 0.95em; }
317
+ :is(.about, #question-text) > :first-child { margin-top: 0; }
309
318
  .about ul, .about ol { margin: 0 0 10px; padding-left: 18px; }
310
319
  .about li { margin: 3px 0; padding-left: 2px; }
311
320
  .about li::marker { color: var(--ink-faint); }
@@ -552,7 +561,24 @@ dialog.question .argument { margin-bottom: 10px; }
552
561
 
553
562
  .auth-field { display: flex; flex-direction: column; gap: 4px; margin: 12px 0; }
554
563
  .auth-field[hidden] { display: none; }
555
- .auth-field > input, .auth-field > select { width: 100%; min-width: 0; }
564
+ .auth-field > input, .auth-field > select {
565
+ width: 100%;
566
+ min-width: 0;
567
+ height: calc(1.5em + 12px);
568
+ line-height: 1.5;
569
+ }
556
570
  .auth-endpoint { overflow-wrap: anywhere; font-family: var(--mono); }
557
571
  .auth-help { color: var(--ink-soft); font-size: 12px; }
558
572
  .auth-error { color: var(--bad); }
573
+
574
+
575
+ dialog.agent-setup { max-width: 680px; width: calc(100vw - 32px); max-height: calc(100vh - 32px); overflow: auto; }
576
+ dialog.agent-setup menu { align-items: center; flex-wrap: wrap; }
577
+ #agent-docs { margin-right: auto; }
578
+ .agent-options { display: grid; grid-template-columns: minmax(0, 1.5fr) repeat(2, minmax(0, 1fr)); gap: 12px; }
579
+ #agent-headers-field[hidden] { display: none; }
580
+ .agent-target { font-family: var(--mono); font-weight: 600; overflow-wrap: anywhere; }
581
+ #agent-code { width: 100%; font-family: var(--mono); font-size: 12px; resize: vertical; }
582
+ @media (max-width: 540px) {
583
+ .agent-options { grid-template-columns: 1fr; gap: 0; }
584
+ }
@@ -736,6 +736,25 @@ function encodeHeader(value) {
736
736
 
737
737
 
738
738
  const page = {
739
+ addAgent: document.getElementById("add-agent"),
740
+ agentSetup: document.getElementById("agent-setup"),
741
+ agentForm: document.getElementById("agent-form"),
742
+ agentMethod: document.getElementById("agent-method"),
743
+ agentLevel: document.getElementById("agent-level"),
744
+ agentName: document.getElementById("agent-name"),
745
+ agentEndpoint: document.getElementById("agent-endpoint"),
746
+ agentHeadersField: document.getElementById("agent-headers-field"),
747
+ agentHeaders: document.getElementById("agent-headers"),
748
+ agentTarget: document.getElementById("agent-target"),
749
+ agentInstructions: document.getElementById("agent-instructions"),
750
+ agentLanguage: document.getElementById("agent-language"),
751
+ agentCode: document.getElementById("agent-code"),
752
+ agentVerify: document.getElementById("agent-verify"),
753
+ agentDocs: document.getElementById("agent-docs"),
754
+ agentError: document.getElementById("agent-error"),
755
+ agentCopyStatus: document.getElementById("agent-copy-status"),
756
+ agentClose: document.getElementById("agent-close"),
757
+ agentCopy: document.getElementById("agent-copy"),
739
758
  serverTitle: document.getElementById("server-title"),
740
759
  authOAuth: document.getElementById("auth-oauth"),
741
760
  authOAuthStatus: document.getElementById("auth-oauth-status"),
@@ -802,6 +821,117 @@ let oauthConfig = null;
802
821
  let oauthMetadata = null;
803
822
  let oauthGeneration = 0;
804
823
  let cancelOAuth = null;
824
+ let agentConnection = null;
825
+
826
+ function agentLevelKey() {
827
+ return `mcp-console-agent-level:${location.pathname}`;
828
+ }
829
+
830
+ function rememberedAgentLevel() {
831
+ try {
832
+ if (localStorage.getItem(agentLevelKey()) === "project") return "project";
833
+ } catch {}
834
+ return "user";
835
+ }
836
+
837
+ function renderAgentSetup() {
838
+ page.agentCopyStatus.textContent = "";
839
+ page.agentError.textContent = "";
840
+ page.agentCode.value = "";
841
+ page.agentCopy.disabled = true;
842
+ page.agentTarget.textContent = "";
843
+ page.agentInstructions.textContent = "";
844
+ page.agentVerify.textContent = "";
845
+ page.agentDocs.hidden = true;
846
+ try {
847
+ if (!agentConnection) return;
848
+ const variants = agentConfigurations({
849
+ endpoint: agentConnection.url,
850
+ level: page.agentLevel.value,
851
+ name: page.agentName.value,
852
+ headers: page.agentHeaders.checked ? agentConnection.headers : {},
853
+ });
854
+ const choice = page.agentMethod.value;
855
+ page.agentMethod.textContent = "";
856
+ for (const variant of variants) {
857
+ const option = element("option", null, variant.label);
858
+ option.value = variant.id;
859
+ page.agentMethod.append(option);
860
+ }
861
+ const variant = variants.find(item => item.id === choice) || variants[0];
862
+ page.agentMethod.value = variant.id;
863
+ page.agentTarget.textContent = `Configuration file: ${variant.target}`;
864
+ page.agentInstructions.textContent = variant.instructions;
865
+ page.agentLanguage.textContent = variant.language.toUpperCase();
866
+ page.agentCode.value = variant.code;
867
+ page.agentVerify.textContent = variant.verify;
868
+ page.agentDocs.href = variant.link;
869
+ page.agentDocs.hidden = false;
870
+ page.agentCopy.disabled = false;
871
+ } catch (error) {
872
+ page.agentError.textContent = error.message;
873
+ }
874
+ }
875
+
876
+ function openAgentSetup() {
877
+ agentConnection = null;
878
+ page.agentMethod.textContent = "";
879
+ page.agentLevel.value = rememberedAgentLevel();
880
+ page.agentHeaders.checked = true;
881
+ page.agentHeadersField.hidden = true;
882
+ page.agentEndpoint.textContent = "";
883
+ page.agentName.value = (page.serverTitle.textContent.trim().toLowerCase()
884
+ .replace(/[^a-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64)) || "mcp";
885
+ renderAgentSetup();
886
+ try {
887
+ const typed = page.endpoint.value.trim() || configuredEndpoint.href;
888
+ const url = new URL(typed, location.origin);
889
+ if (url.origin !== location.origin) throw new Error("The endpoint must be on this server.");
890
+ if (url.username || url.password) throw new Error("Enter credentials through Authentication.");
891
+ url.hash = "";
892
+ const saved = new ConsoleCredentials();
893
+ saved.restore(url.href);
894
+ const headers = credentials.endpoint === url.href
895
+ ? credentials.forEndpoint(url.href) : saved.forEndpoint(url.href);
896
+ agentConnection = {url: url.href, headers};
897
+ page.agentEndpoint.textContent = url.href;
898
+ page.agentHeadersField.hidden = !Object.keys(headers).length;
899
+ renderAgentSetup();
900
+ } catch (error) {
901
+ page.agentError.textContent = error.message;
902
+ }
903
+ if (!page.agentSetup.open) page.agentSetup.showModal();
904
+ }
905
+
906
+ function setupAgentDialog() {
907
+ if (!page.addAgent || !page.agentSetup) return;
908
+ page.addAgent.onclick = openAgentSetup;
909
+ page.agentMethod.onchange = renderAgentSetup;
910
+ page.agentLevel.onchange = () => {
911
+ try { localStorage.setItem(agentLevelKey(), page.agentLevel.value); } catch {}
912
+ renderAgentSetup();
913
+ };
914
+ page.agentName.oninput = renderAgentSetup;
915
+ page.agentHeaders.onchange = renderAgentSetup;
916
+ page.agentClose.onclick = () => page.agentSetup.close();
917
+ page.agentForm.onsubmit = event => event.preventDefault();
918
+ page.agentSetup.addEventListener("close", () => {
919
+ agentConnection = null;
920
+ page.agentCode.value = "";
921
+ page.agentEndpoint.textContent = "";
922
+ });
923
+ page.agentCopy.onclick = async () => {
924
+ if (!page.agentCode.value) return;
925
+ try {
926
+ await navigator.clipboard.writeText(page.agentCode.value);
927
+ page.agentCopyStatus.textContent = "Configuration copied.";
928
+ } catch {
929
+ page.agentCode.focus();
930
+ page.agentCode.select();
931
+ page.agentCopyStatus.textContent = "Copy the selected configuration with your keyboard.";
932
+ }
933
+ };
934
+ }
805
935
 
806
936
  function resetOAuth() {
807
937
  oauthGeneration++;
@@ -1621,11 +1751,18 @@ function markdownHtml(text) {
1621
1751
  continue;
1622
1752
  }
1623
1753
 
1624
- const heading = line.match(/^(#{1,6})\s+(.*)$/);
1625
- if (heading) {
1754
+ const heading = line.match(/^ {0,3}(#{1,7})(?:[\t ]+(.*)|[\t ]*)$/);
1755
+ const headingTag = line.match(/^ {0,3}<h([1-7])>(.*?)<\/h\1>[\t ]*$/i);
1756
+ if (heading || headingTag) {
1626
1757
  endBoth();
1627
- const level = Math.min(heading[1].length + 2, 6); // the panel owns h1 and h2
1628
- out.push(`<h${level}>${inline(escapeHtml(heading[2]))}</h${level}>`);
1758
+ const level = heading ? heading[1].length : Number(headingTag[1]);
1759
+ const content = heading
1760
+ ? (heading[2] || "").replace(/[\t ]+#+[\t ]*$/, "").trim()
1761
+ : headingTag[2];
1762
+ const rendered = inline(escapeHtml(content));
1763
+ out.push(level === 7
1764
+ ? `<div role="heading" aria-level="7">${rendered}</div>`
1765
+ : `<h${level}>${rendered}</h${level}>`);
1629
1766
  continue;
1630
1767
  }
1631
1768
 
@@ -1673,7 +1810,7 @@ function plain(text) {
1673
1810
  .replace(/`([^`]+)`/g, "$1")
1674
1811
  .replace(/\*\*([^*]+)\*\*/g, "$1")
1675
1812
  .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
1676
- .replace(/^#{1,6}\s+/, "")
1813
+ .replace(/^#{1,7}\s+/, "")
1677
1814
  .replace(/^\s*[-*+]\s+/, "");
1678
1815
  }
1679
1816
 
@@ -2277,7 +2414,39 @@ function showServerInstructions(clearFragment = true) {
2277
2414
  if (catalogue) catalogue.fold();
2278
2415
  }
2279
2416
 
2417
+ function rememberConnection(connected) {
2418
+ try {
2419
+ const key = `mcp-console-connection:${location.pathname}`;
2420
+ if (!connected) {
2421
+ sessionStorage.removeItem(key);
2422
+ return;
2423
+ }
2424
+ sessionStorage.setItem(key, JSON.stringify({
2425
+ endpoint: endpointUrl.href,
2426
+ revision: page.revision.value,
2427
+ answerable: page.answerable.checked,
2428
+ notifications: page.notifications.checked,
2429
+ }));
2430
+ } catch {}
2431
+ }
2432
+
2433
+ function restoreConnection() {
2434
+ try {
2435
+ const saved = JSON.parse(sessionStorage.getItem(`mcp-console-connection:${location.pathname}`));
2436
+ if (!saved || typeof saved.endpoint !== "string" || !REVISIONS[saved.revision]
2437
+ || typeof saved.answerable !== "boolean" || typeof saved.notifications !== "boolean") return;
2438
+ const url = new URL(saved.endpoint);
2439
+ if (url.origin !== location.origin || url.username || url.password || url.hash) return;
2440
+ page.endpoint.value = url.pathname + url.search;
2441
+ page.revision.value = saved.revision;
2442
+ page.answerable.checked = saved.answerable;
2443
+ page.notifications.checked = saved.notifications;
2444
+ connect();
2445
+ } catch {}
2446
+ }
2447
+
2280
2448
  function disconnect() {
2449
+ rememberConnection(false);
2281
2450
  // Sessions expire server-side; there is no close request.
2282
2451
  client?.abort.abort();
2283
2452
  client = null;
@@ -2300,6 +2469,7 @@ function disconnect() {
2300
2469
  }
2301
2470
 
2302
2471
  async function connect() {
2472
+ rememberConnection(false);
2303
2473
  page.connect.disabled = true;
2304
2474
  page.authenticate.disabled = true;
2305
2475
  page.revision.disabled = true;
@@ -2331,6 +2501,7 @@ async function connect() {
2331
2501
  page.connect.textContent = "Disconnect";
2332
2502
  if (!chosen) showServerInstructions(false);
2333
2503
  client.startNotifications();
2504
+ rememberConnection(true);
2334
2505
  } catch (error) {
2335
2506
  client?.abort.abort();
2336
2507
  setServerInstructions("");
@@ -2414,6 +2585,7 @@ function markTraffic() {
2414
2585
  function start() {
2415
2586
  if (page.serverTitle) page.serverTitle.onclick = () => showServerInstructions();
2416
2587
  setupAuthentication();
2588
+ setupAgentDialog();
2417
2589
  Object.keys(REVISIONS).forEach((version) => {
2418
2590
  const option = element("option", null, version);
2419
2591
  option.value = version;
@@ -2470,6 +2642,7 @@ function start() {
2470
2642
  page.revision.onchange = () => {
2471
2643
  try { localStorage.setItem("mcp-console-revision", page.revision.value); } catch {}
2472
2644
  };
2645
+ restoreConnection();
2473
2646
  }
2474
2647
 
2475
2648
  if (document.documentElement.dataset.oauthCallback === "true") {
@@ -29,6 +29,7 @@
29
29
  </label>
30
30
  <button id="connect" class="primary">Connect</button>
31
31
  <button id="authenticate" class="quiet" type="button">Authentication</button>
32
+ <button id="add-agent" class="quiet" type="button">Add agent</button>
32
33
  <span id="status" class="status">not connected</span>
33
34
  </header>
34
35
 
@@ -140,6 +141,46 @@
140
141
  </form>
141
142
  </dialog>
142
143
 
144
+ <dialog id="agent-setup" class="question agent-setup" aria-labelledby="agent-title">
145
+ <form id="agent-form" autocomplete="off">
146
+ <h2 id="agent-title">Add agent</h2>
147
+ <p class="auth-help">Connect an agent to this MCP endpoint.</p>
148
+ <p id="agent-endpoint" class="auth-endpoint"></p>
149
+ <div class="agent-options">
150
+ <label class="auth-field">Agent
151
+ <select id="agent-method"></select>
152
+ </label>
153
+ <label class="auth-field">Configuration level
154
+ <select id="agent-level">
155
+ <option value="user">User</option>
156
+ <option value="project">Project</option>
157
+ </select>
158
+ </label>
159
+ <label class="auth-field">Server name
160
+ <input id="agent-name" type="text" spellcheck="false" maxlength="64" required>
161
+ </label>
162
+ </div>
163
+ <label id="agent-headers-field" class="toggle" hidden>
164
+ <input id="agent-headers" type="checkbox" checked>
165
+ <span>Include saved authentication headers</span>
166
+ </label>
167
+ <p id="agent-target" class="agent-target"></p>
168
+ <p id="agent-instructions"></p>
169
+ <label class="auth-field"><span id="agent-language">Configuration</span>
170
+ <textarea id="agent-code" rows="12" readonly spellcheck="false" wrap="off"></textarea>
171
+ </label>
172
+ <p id="agent-verify" class="auth-help"></p>
173
+ <p id="agent-error" class="auth-error" role="alert"></p>
174
+ <p id="agent-copy-status" class="auth-help" role="status"></p>
175
+ <menu>
176
+ <a id="agent-docs" target="_blank" rel="noopener noreferrer">Agent documentation</a>
177
+ <button id="agent-close" class="quiet" type="button">Close</button>
178
+ <button id="agent-copy" class="primary" type="button">Copy configuration</button>
179
+ </menu>
180
+ </form>
181
+ </dialog>
182
+
183
+ <script src="{{BASE}}/agent-config.js"></script>
143
184
  <script src="{{BASE}}/console.js"></script>
144
185
  </body>
145
186
  </html>
@@ -97,6 +97,7 @@ class Adapter(ABC):
97
97
  FailureKind.UNKNOWN_METHOD: (-32601, 200),
98
98
  FailureKind.UNKNOWN_TARGET: (-32601, 200),
99
99
  FailureKind.RESOURCE_NOT_FOUND: (-32002, 200),
100
+ FailureKind.ACCESS_DENIED: (-32003, 403),
100
101
  FailureKind.HEADER_MISMATCH: (-32603, 200),
101
102
  FailureKind.UNSUPPORTED_VERSION: (-32600, 400),
102
103
  FailureKind.INPUT_UNSUPPORTED: (-32603, 200),
@@ -84,6 +84,7 @@ class FailureKind(StringEnum):
84
84
  UNKNOWN_METHOD = "unknown_method"
85
85
  UNKNOWN_TARGET = "unknown_target"
86
86
  RESOURCE_NOT_FOUND = "resource_not_found"
87
+ ACCESS_DENIED = "access_denied"
87
88
  INVALID_PARAMS = "invalid_params"
88
89
  INVALID_ARGUMENTS = "invalid_arguments"
89
90
  HEADER_MISMATCH = "header_mismatch"
@@ -24,6 +24,7 @@ from aiohttp_tiny_mcp.protocol.core import (
24
24
  )
25
25
  from aiohttp_tiny_mcp.protocol.models import (
26
26
  CallToolResult,
27
+ CompleteParams,
27
28
  CompleteResult,
28
29
  Completion,
29
30
  EmptyResult,
@@ -48,6 +49,7 @@ from aiohttp_tiny_mcp.protocol.models import (
48
49
  from .exchange import Exchange
49
50
  from .registry import Registry
50
51
  from .request_state import RequestStates, protect_request_state, restore_request_state
52
+ from .resource_auth import resource_refusal, visible_resource
51
53
  from .specs import ToolSpec
52
54
  from .subscriptions import listen, subscribe, unsubscribe
53
55
 
@@ -244,12 +246,11 @@ class Dispatcher:
244
246
  "resources/subscribe needs the session the handshake issued",
245
247
  )
246
248
  if wanted:
247
- found = self.registry.match_resource(uri)
248
- definition = ex.adapter.describe_resource(found[0]) if found is not None else None
249
- if definition is None or (
250
- isinstance(definition, ResourceDef) and definition.uri != uri
251
- ):
249
+ spec = visible_resource(self.registry, ex.adapter, uri)
250
+ if spec is None:
252
251
  return Failure(FailureKind.RESOURCE_NOT_FOUND, f"no resource matches {uri}")
252
+ if (refused := resource_refusal(spec, ex.principal)) is not None:
253
+ return Failure(FailureKind.ACCESS_DENIED, refused)
253
254
  await (subscribe if wanted else unsubscribe)(ex.session, uri)
254
255
  return Value(result=EmptyResult())
255
256
 
@@ -344,13 +345,10 @@ class Dispatcher:
344
345
  if found is None:
345
346
  return Failure(FailureKind.RESOURCE_NOT_FOUND, f"resource not found: {uri}")
346
347
  spec, variables = found
347
- definition = ex.adapter.describe_resource(spec)
348
- if definition is None or (isinstance(definition, ResourceDef) and definition.uri != uri):
348
+ if visible_resource(self.registry, ex.adapter, uri) is None:
349
349
  return Failure(FailureKind.RESOURCE_NOT_FOUND, f"resource not found: {uri}")
350
- if spec.template is not None and spec.legacy_uri is not None:
351
- pattern = spec.pattern if ex.adapter.supports_extensions else spec.legacy_pattern
352
- if pattern is None or pattern.fullmatch(uri) is None:
353
- return Failure(FailureKind.RESOURCE_NOT_FOUND, f"resource not found: {uri}")
350
+ if (refused := resource_refusal(spec, ex.principal)) is not None:
351
+ return Failure(FailureKind.ACCESS_DENIED, refused)
354
352
  try:
355
353
  value = await spec.bound.call(variables, ex)
356
354
  except ValidationError as e:
@@ -381,6 +379,18 @@ class Dispatcher:
381
379
  return Value(result=prompt_result(value))
382
380
 
383
381
  async def complete(self, ex: Exchange) -> Outcome:
382
+ if isinstance(ex.call.params, CompleteParams) and ex.call.params.ref.type == "ref/resource":
383
+ uri = ex.call.params.ref.uri or ""
384
+ spec = visible_resource(self.registry, ex.adapter, uri, template=True)
385
+ if spec is not None:
386
+ if (refused := resource_refusal(spec, ex.principal)) is not None:
387
+ return Failure(FailureKind.ACCESS_DENIED, refused)
388
+ elif self.registry.match_resource(uri) is not None or any(
389
+ candidate.template is not None
390
+ and uri in (candidate.template.uri_template, candidate.legacy_uri)
391
+ for candidate in self.registry.resources_templated
392
+ ):
393
+ return Failure(FailureKind.RESOURCE_NOT_FOUND, f"resource not found: {uri}")
384
394
  completer = self.registry.completer
385
395
  if completer is None:
386
396
  return Value(result=CompleteResult(completion=Completion(values=[])))
@@ -48,6 +48,7 @@ from aiohttp_tiny_mcp.transport.sse import SSEResponse
48
48
  from .dispatcher import Dispatcher
49
49
  from .exchange import Exchange, is_reply, relay_reply
50
50
  from .registry import Registry
51
+ from .resource_auth import allowed_resource
51
52
  from .subscriptions import relays, wanted
52
53
  from .tasks import stop
53
54
 
@@ -451,7 +452,9 @@ class Endpoint:
451
452
 
452
453
  response = SSEResponse(compress=self.compress)
453
454
  await response.prepare(request)
454
- relay = asyncio.create_task(self.relay_notifications(request, response, adapter))
455
+ relay = asyncio.create_task(
456
+ self.relay_notifications(request, response, adapter, principal=principal)
457
+ )
455
458
  try:
456
459
  while not relay.done():
457
460
  await asyncio.wait({relay}, timeout=0.05)
@@ -463,7 +466,12 @@ class Endpoint:
463
466
  return response
464
467
 
465
468
  async def relay_notifications(
466
- self, request: web.Request, response: SSEResponse, adapter: Adapter
469
+ self,
470
+ request: web.Request,
471
+ response: SSEResponse,
472
+ adapter: Adapter,
473
+ *,
474
+ principal: Principal | None = None,
467
475
  ) -> None:
468
476
  """Relay changes with their hub ids, re-reading subscriptions each pass."""
469
477
  capabilities = adapter.capabilities(self.registry)
@@ -477,6 +485,12 @@ class Endpoint:
477
485
  self.open_values(request, await self.stored(request)),
478
486
  self.registry.broadcasts,
479
487
  )
488
+ if "resourceSubscriptions" in accepted:
489
+ accepted["resourceSubscriptions"] = [
490
+ uri
491
+ for uri in accepted["resourceSubscriptions"]
492
+ if allowed_resource(self.registry, adapter, uri, principal)
493
+ ]
480
494
  for event in found:
481
495
  if relays(event.message, accepted):
482
496
  text = serialized(event.message).decode()
@@ -132,6 +132,11 @@ class Registry:
132
132
  }
133
133
  claimed: set[str] = set()
134
134
  for uri, resource in resources.items():
135
+ if resource.scopes and self.auth is None:
136
+ raise TypeError(
137
+ f"{uri}: scopes were declared, but this registry has no auth= -- "
138
+ f"a scope nothing verifies is a check that never runs"
139
+ )
135
140
  for address in {uri, resource.legacy_uri}:
136
141
  if address is None:
137
142
  continue
@@ -259,6 +264,11 @@ class Registry:
259
264
  def resource(self, uri: str, fn: Callable[..., Awaitable[Any]] | None = None, **kw: Any):
260
265
  def register(fn: Callable[..., Awaitable[Any]]):
261
266
  spec = ResourceSpec.build(uri, fn, **kw)
267
+ if spec.scopes and self.auth is None:
268
+ raise TypeError(
269
+ f"{uri}: scopes were declared, but this registry has no auth= -- "
270
+ f"a scope nothing verifies is a check that never runs"
271
+ )
262
272
  self.check(uri, spec.bound)
263
273
  if spec.definition is not None:
264
274
  if (
@@ -0,0 +1,68 @@
1
+ """Resource visibility and authorization shared by calls and notification streams."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from aiohttp_tiny_mcp.auth import Principal
8
+ from aiohttp_tiny_mcp.protocol.models import ResourceDef, ResourceTemplateDef
9
+
10
+ if TYPE_CHECKING:
11
+ from aiohttp_tiny_mcp.protocol.adapter import Adapter, RegistryProtocol
12
+
13
+ from .specs import ResourceSpec
14
+
15
+
16
+ def visible_resource(
17
+ registry: RegistryProtocol, adapter: Adapter, uri: str, *, template: bool = False
18
+ ) -> ResourceSpec | None:
19
+ """Resolve a resource using only the URI spelling exposed by this revision."""
20
+ if template:
21
+ for spec in registry.resources_templated:
22
+ if spec.template is None or uri not in (spec.template.uri_template, spec.legacy_uri):
23
+ continue
24
+ definition = adapter.describe_resource(spec)
25
+ if isinstance(definition, ResourceTemplateDef) and definition.uri_template == uri:
26
+ return spec
27
+ return None
28
+ found = registry.match_resource(uri)
29
+ if found is None:
30
+ return None
31
+ spec = found[0]
32
+ definition = adapter.describe_resource(spec)
33
+ if definition is None:
34
+ return None
35
+ if isinstance(definition, ResourceDef):
36
+ return spec if definition.uri == uri else None
37
+ pattern = spec.pattern
38
+ if spec.legacy_uri is not None and not adapter.supports_extensions:
39
+ pattern = spec.legacy_pattern
40
+ return spec if pattern is not None and pattern.fullmatch(uri) is not None else None
41
+
42
+
43
+ def resource_refusal(spec: ResourceSpec, principal: Principal | None) -> str | None:
44
+ """Describe a resource scope failure without invoking its handler or dependencies."""
45
+ if not spec.scopes:
46
+ return None
47
+ label = "resource"
48
+ if spec.definition is not None:
49
+ label = spec.definition.uri
50
+ elif spec.template is not None:
51
+ label = spec.template.uri_template
52
+ if principal is None:
53
+ return (
54
+ f"{label} requires the scopes {', '.join(sorted(spec.scopes))}, and this "
55
+ f"request carried no verified caller"
56
+ )
57
+ missing = principal.holds(spec.scopes)
58
+ if missing:
59
+ return f"{label} requires the scope {', '.join(sorted(missing))}"
60
+ return None
61
+
62
+
63
+ def allowed_resource(
64
+ registry: RegistryProtocol, adapter: Adapter, uri: str, principal: Principal | None
65
+ ) -> bool:
66
+ """Check a concrete resource URI before including it in a notification stream."""
67
+ spec = visible_resource(registry, adapter, uri)
68
+ return spec is not None and resource_refusal(spec, principal) is None
@@ -156,6 +156,7 @@ class ResourceSpec(Model):
156
156
  model_config = ConfigDict(arbitrary_types_allowed=True)
157
157
 
158
158
  bound: Bound
159
+ scopes: frozenset[str] = Field(default_factory=frozenset)
159
160
  definition: ResourceDef | None = None # fixed URI
160
161
  template: ResourceTemplateDef | None = None # URI template
161
162
  pattern: Any = None # compiled matcher for the template
@@ -180,13 +181,18 @@ class ResourceSpec(Model):
180
181
  mime_type: str | None = None,
181
182
  cache_ttl_ms: int | None = None,
182
183
  cache_scope: Literal["public", "private"] | None = None,
184
+ scopes: Iterable[str] | None = None,
183
185
  ) -> ResourceSpec:
186
+ required = frozenset(scopes or ())
187
+ if required and cache_scope == "public":
188
+ raise ValueError("Resources with scopes cannot use public caching.")
184
189
  bound = Bound.of(fn)
185
190
  name = name or getattr(fn, "__name__", repr(fn))
186
191
  description = described(description, fn) or None
187
192
  if not cls.VAR.search(uri):
188
193
  return cls(
189
194
  bound=bound,
195
+ scopes=required,
190
196
  mime_type=mime_type,
191
197
  cache_ttl_ms=cache_ttl_ms,
192
198
  cache_scope=cache_scope,
@@ -202,6 +208,7 @@ class ResourceSpec(Model):
202
208
  parts.append(re.escape(uri[last:]))
203
209
  return cls(
204
210
  bound=bound,
211
+ scopes=required,
205
212
  mime_type=mime_type,
206
213
  cache_ttl_ms=cache_ttl_ms,
207
214
  cache_scope=cache_scope,
@@ -43,6 +43,7 @@ from .dispatcher import Dispatcher
43
43
  from .exchange import Exchange
44
44
  from .http import Endpoint
45
45
  from .registry import Registry
46
+ from .resource_auth import allowed_resource
46
47
  from .subscriptions import relays, wanted
47
48
  from .tasks import stop
48
49
 
@@ -127,7 +128,7 @@ class SseEndpoint:
127
128
  await self.relay_until_disconnect(
128
129
  request,
129
130
  self.relay(response, events),
130
- self.relay_shared(response, shared, session_id),
131
+ self.relay_shared(response, shared, session_id, principal=principal),
131
132
  )
132
133
  finally:
133
134
  await hub.delete(where)
@@ -164,7 +165,12 @@ class SseEndpoint:
164
165
  await self.write(response, "message", json.dumps(event.message, ensure_ascii=False))
165
166
 
166
167
  async def relay_shared(
167
- self, response: SSEResponse, events: Subscription, session_id: str
168
+ self,
169
+ response: SSEResponse,
170
+ events: Subscription,
171
+ session_id: str,
172
+ *,
173
+ principal: Principal | None = None,
168
174
  ) -> None:
169
175
  """Write the list changes, resource updates and broadcasts this session wants.
170
176
 
@@ -184,6 +190,12 @@ class SseEndpoint:
184
190
  accepted = wanted(
185
191
  adapter.capabilities(self.registry), session, self.registry.broadcasts
186
192
  )
193
+ if "resourceSubscriptions" in accepted:
194
+ accepted["resourceSubscriptions"] = [
195
+ uri
196
+ for uri in accepted["resourceSubscriptions"]
197
+ if allowed_resource(self.registry, adapter, uri, principal)
198
+ ]
187
199
  for event in found:
188
200
  if relays(event.message, accepted):
189
201
  text = serialized(event.message).decode()
@@ -15,6 +15,8 @@ from aiohttp_tiny_mcp.protocol.models import EmptyResult, ListenParams, Meta, Me
15
15
  from aiohttp_tiny_mcp.storage import hub as hubs
16
16
  from aiohttp_tiny_mcp.storage.sessions import SUBSCRIPTIONS_KEY, Session
17
17
 
18
+ from .resource_auth import allowed_resource
19
+
18
20
  if TYPE_CHECKING:
19
21
  from .exchange import Exchange
20
22
 
@@ -116,7 +118,11 @@ async def listen(ex: Exchange) -> EmptyResult:
116
118
  if requested.get(field) and caps.get(capability, {}).get("listChanged"):
117
119
  accepted[field] = True
118
120
  if caps.get("resources", {}).get("subscribe"):
119
- uris = [uri for uri in wanted.resource_subscriptions if ex.registry.match_resource(uri)]
121
+ uris = [
122
+ uri
123
+ for uri in wanted.resource_subscriptions
124
+ if allowed_resource(ex.registry, ex.adapter, uri, ex.principal)
125
+ ]
120
126
  if uris:
121
127
  accepted["resourceSubscriptions"] = list(dict.fromkeys(uris))
122
128
  declared = broadcasts_for(ex)