@musashishao/agent-kit 1.9.0 → 1.9.1

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 (125) hide show
  1. package/.agent/agents/ai-asset-factory.md +700 -0
  2. package/.agent/agents/ai-audio-factory.md +503 -0
  3. package/.agent/agents/game-developer.md +4 -4
  4. package/.agent/agents/orchestrator.md +113 -3
  5. package/.agent/agents/project-planner.md +67 -0
  6. package/.agent/agents/unity-mobile-master.md +949 -0
  7. package/.agent/mcp/config/registry.json +65 -51
  8. package/.agent/mcp/servers/notebooklm/README.md +114 -0
  9. package/.agent/mcp/servers/notebooklm/package.json +35 -0
  10. package/.agent/mcp/servers/notebooklm/src/auth/chrome.ts +225 -0
  11. package/.agent/mcp/servers/notebooklm/src/auth/index.ts +1 -0
  12. package/.agent/mcp/servers/notebooklm/src/index.ts +516 -0
  13. package/.agent/mcp/servers/notebooklm/src/services/index.ts +3 -0
  14. package/.agent/mcp/servers/notebooklm/src/services/library.ts +217 -0
  15. package/.agent/mcp/servers/notebooklm/src/services/notebooklm.ts +380 -0
  16. package/.agent/mcp/servers/notebooklm/tsconfig.json +15 -0
  17. package/.agent/mcp-gateway/README.md +169 -20
  18. package/.agent/mcp-gateway/package.json +22 -7
  19. package/.agent/mcp-gateway/src/auth/index.ts +55 -0
  20. package/.agent/mcp-gateway/src/auth/middleware.ts +242 -0
  21. package/.agent/mcp-gateway/src/auth/oauth.ts +462 -0
  22. package/.agent/mcp-gateway/src/auth/scopes.ts +227 -0
  23. package/.agent/mcp-gateway/src/index.ts +252 -105
  24. package/.agent/mcp-gateway/src/observability/index.ts +5 -0
  25. package/.agent/mcp-gateway/src/observability/otel.ts +405 -0
  26. package/.agent/mcp-gateway/src/transports/index.ts +5 -0
  27. package/.agent/mcp-gateway/src/transports/streamableHttp.ts +235 -0
  28. package/.agent/rules/CODEX.md +89 -0
  29. package/.agent/rules/CODE_RULES.md +73 -0
  30. package/.agent/rules/GEMINI.md +25 -0
  31. package/.agent/rules/MEMORY_STATE.md +110 -0
  32. package/.agent/rules/REFERENCE.md +33 -141
  33. package/.agent/rules/REF_SKILLS.md +116 -0
  34. package/.agent/rules/REF_WORKFLOWS.md +81 -0
  35. package/.agent/scripts/ak_cli.py +106 -5
  36. package/.agent/scripts/memory_manager.py +48 -9
  37. package/.agent/skills/anti-hallucination/SKILL.md +295 -0
  38. package/.agent/skills/anti-hallucination/scripts/check_hallucination.py +299 -0
  39. package/.agent/skills/bifurcation-analysis/SKILL.md +56 -0
  40. package/.agent/skills/brainstorming/SKILL.md +80 -6
  41. package/.agent/skills/decision-memory/SKILL.md +317 -0
  42. package/.agent/skills/emergence-detector/SKILL.md +230 -0
  43. package/.agent/skills/emergence-detector/scripts/check_emergence.py +265 -0
  44. package/.agent/skills/explained-qa/SKILL.md +142 -0
  45. package/.agent/skills/explained-qa/game-terminology.md +214 -0
  46. package/.agent/skills/game-development/ai-dialogue-engine/SKILL.md +442 -0
  47. package/.agent/skills/game-development/ai-graphics-generator/SKILL.md +463 -0
  48. package/.agent/skills/game-development/ai-playtest-framework/SKILL.md +570 -0
  49. package/.agent/skills/game-development/camera-systems/SKILL.md +607 -0
  50. package/.agent/skills/game-development/card-battle-engine/SKILL.md +618 -0
  51. package/.agent/skills/game-development/character-controller-3d/SKILL.md +908 -0
  52. package/.agent/skills/game-development/cloud-save-sync/SKILL.md +527 -0
  53. package/.agent/skills/game-development/combat-system/SKILL.md +748 -0
  54. package/.agent/skills/game-development/compliance-rating/SKILL.md +277 -0
  55. package/.agent/skills/game-development/crossplatform-build/SKILL.md +386 -0
  56. package/.agent/skills/game-development/cultivation-progression/SKILL.md +520 -0
  57. package/.agent/skills/game-development/data-driven-balance/SKILL.md +535 -0
  58. package/.agent/skills/game-development/game-analytics-integrator/SKILL.md +410 -0
  59. package/.agent/skills/game-development/game-audio-advanced/SKILL.md +646 -0
  60. package/.agent/skills/game-development/game-economy-designer/SKILL.md +375 -0
  61. package/.agent/skills/game-development/game-marketing/SKILL.md +85 -0
  62. package/.agent/skills/game-development/game-state-manager/SKILL.md +883 -0
  63. package/.agent/skills/game-development/hybrid-game-spec/SKILL.md +220 -0
  64. package/.agent/skills/game-development/inventory-quest/SKILL.md +747 -0
  65. package/.agent/skills/game-development/liveops/SKILL.md +308 -0
  66. package/.agent/skills/game-development/localization/SKILL.md +286 -0
  67. package/.agent/skills/game-development/mobile-input-patterns/SKILL.md +343 -0
  68. package/.agent/skills/game-development/monetization-strategy/SKILL.md +94 -0
  69. package/.agent/skills/game-development/multiplayer-master/SKILL.md +727 -0
  70. package/.agent/skills/game-development/narrative-branching/SKILL.md +593 -0
  71. package/.agent/skills/game-development/procedural-level-ai/SKILL.md +367 -0
  72. package/.agent/skills/game-development/prototyping-rapid/SKILL.md +205 -0
  73. package/.agent/skills/game-development/spec-ecosystem/SKILL.md +155 -0
  74. package/.agent/skills/game-development/spec-ecosystem/decision-log-format.md +129 -0
  75. package/.agent/skills/game-development/spec-ecosystem/templates/PLAN-template.md +178 -0
  76. package/.agent/skills/game-development/spec-ecosystem/templates/SPEC-template.md +110 -0
  77. package/.agent/skills/game-development/spec-ecosystem/templates/TASKS-template.md +156 -0
  78. package/.agent/skills/game-development/survival-systems/SKILL.md +493 -0
  79. package/.agent/skills/game-development/testing-qa/SKILL.md +270 -0
  80. package/.agent/skills/game-development/unity-mobile-optimization/SKILL.md +271 -0
  81. package/.agent/skills/intent-capture/SKILL.md +65 -0
  82. package/.agent/skills/mcp-composition/SKILL.md +362 -0
  83. package/.agent/skills/mcp-observability/SKILL.md +323 -0
  84. package/.agent/skills/mcp-security/SKILL.md +314 -0
  85. package/.agent/skills/trust-spectrum/SKILL.md +291 -0
  86. package/.agent/skills/vibe-coding-guard/SKILL.md +328 -0
  87. package/.agent/templates/AGENTS.game.md +63 -0
  88. package/.agent/templates/docs/WORKFLOW_GUIDE.en.md +100 -0
  89. package/.agent/templates/docs/WORKFLOW_GUIDE.vi.md +100 -0
  90. package/.agent/workflows/ai-agent.md +2 -0
  91. package/.agent/workflows/autofix.md +1 -0
  92. package/.agent/workflows/brainstorm.md +1 -0
  93. package/.agent/workflows/context.md +1 -0
  94. package/.agent/workflows/create.md +39 -8
  95. package/.agent/workflows/dashboard.md +1 -0
  96. package/.agent/workflows/debug.md +14 -0
  97. package/.agent/workflows/deploy.md +14 -0
  98. package/.agent/workflows/enhance.md +44 -0
  99. package/.agent/workflows/gamekit-init.md +177 -0
  100. package/.agent/workflows/gamekit-launch.md +338 -0
  101. package/.agent/workflows/gamekit-plan.md +204 -0
  102. package/.agent/workflows/gamekit-qa.md +153 -0
  103. package/.agent/workflows/gamekit-spec.md +243 -0
  104. package/.agent/workflows/gamekit-tasks.md +208 -0
  105. package/.agent/workflows/marketing.md +2 -0
  106. package/.agent/workflows/next.md +1 -0
  107. package/.agent/workflows/orchestrate.md +12 -0
  108. package/.agent/workflows/pentest.md +2 -0
  109. package/.agent/workflows/plan.md +42 -0
  110. package/.agent/workflows/preview.md +1 -0
  111. package/.agent/workflows/quality.md +1 -0
  112. package/.agent/workflows/saas.md +2 -0
  113. package/.agent/workflows/spec.md +42 -0
  114. package/.agent/workflows/status.md +1 -0
  115. package/.agent/workflows/test.md +14 -0
  116. package/.agent/workflows/ui-ux-pro-max.md +1 -0
  117. package/bin/cli.js +411 -111
  118. package/package.json +1 -2
  119. package/.agent/agents/game-asset-curator.md +0 -317
  120. package/.agent/agents/game-narrative-designer.md +0 -310
  121. package/.agent/agents/game-qa-agent.md +0 -441
  122. package/.agent/workflows/game-prototype.md +0 -154
  123. package/docs/AI_DATA_INFRASTRUCTURE.md +0 -288
  124. package/docs/CHANGELOG_AI_INFRA.md +0 -141
  125. package/docs/MIGRATION_GUIDE_V1.9.md +0 -55
@@ -1,14 +1,26 @@
1
- # Agent Kit MCP Gateway
1
+ # Agent Kit MCP Gateway v2.0
2
2
 
3
- > Live Project Cortex - MCP Server providing real-time project context to AI agents.
3
+ > Enterprise-grade MCP Server with OAuth 2.1, Streamable HTTP, and OpenTelemetry
4
+
5
+ ## 🚀 What's New in v2.0
6
+
7
+ | Feature | Description |
8
+ |---------|-------------|
9
+ | **Streamable HTTP** | Modern transport for remote/production use |
10
+ | **OAuth 2.1 + API Keys** | Enterprise security with scope-based access |
11
+ | **OpenTelemetry** | Distributed tracing and metrics |
12
+ | **New Tools** | `force_sync`, `get_metrics`, `get_server_info` |
4
13
 
5
14
  ## Features
6
15
 
7
16
  - **get_project_context** - Read AGENTS.md sections
17
+ - **get_project_intelligence** - Code/Docs distribution analysis
8
18
  - **analyze_dependencies** - Query dependency graph
9
- - **search_code_logic** - Semantic code search
19
+ - **search_knowledge** - Semantic code search
10
20
  - **get_impact_zone** - Impact analysis for changes
11
21
  - **force_sync** - Refresh all AI data
22
+ - **get_metrics** - Server performance metrics
23
+ - **get_server_info** - Server capabilities
12
24
 
13
25
  ## Installation
14
26
 
@@ -20,7 +32,32 @@ npm run build
20
32
 
21
33
  ## Usage
22
34
 
23
- ### With Claude Desktop
35
+ ### Local Development (stdio)
36
+
37
+ ```bash
38
+ npm run dev
39
+ ```
40
+
41
+ ### Production (HTTP)
42
+
43
+ ```bash
44
+ MCP_ENABLE_HTTP=true MCP_HTTP_PORT=3100 npm run start:http
45
+ ```
46
+
47
+ ### Environment Variables
48
+
49
+ | Variable | Description | Default |
50
+ |----------|-------------|---------|
51
+ | `PROJECT_ROOT` | Path to project root | Current directory |
52
+ | `MCP_ENABLE_HTTP` | Enable HTTP transport | `false` |
53
+ | `MCP_HTTP_PORT` | HTTP port | `3100` |
54
+ | `MCP_ENABLE_AUTH` | Enable authentication | `false` |
55
+ | `MCP_API_KEY` | Default API key | - |
56
+ | `MCP_CORS_ORIGINS` | Comma-separated CORS origins | - |
57
+
58
+ ## Configuration
59
+
60
+ ### Claude Desktop (stdio)
24
61
 
25
62
  Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
26
63
 
@@ -38,7 +75,7 @@ Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
38
75
  }
39
76
  ```
40
77
 
41
- ### With Cursor
78
+ ### Cursor (stdio)
42
79
 
43
80
  Add to `.cursor/mcp.json`:
44
81
 
@@ -56,22 +93,65 @@ Add to `.cursor/mcp.json`:
56
93
  }
57
94
  ```
58
95
 
59
- ### Development
96
+ ### Remote Client (HTTP)
97
+
98
+ ```typescript
99
+ // Connect to HTTP transport
100
+ const client = new MCPClient({
101
+ transport: "http",
102
+ url: "http://localhost:3100/mcp",
103
+ auth: {
104
+ type: "api-key",
105
+ key: process.env.MCP_API_KEY,
106
+ }
107
+ });
108
+ ```
109
+
110
+ ## Security
111
+
112
+ ### API Key Authentication
60
113
 
61
114
  ```bash
62
- # Run in dev mode
63
- npm run dev
115
+ # Set API key
116
+ export MCP_API_KEY="your-secret-key"
117
+ export MCP_ENABLE_AUTH=true
64
118
 
65
- # Build for production
66
- npm run build
119
+ # Client usage
120
+ curl -X POST http://localhost:3100/mcp \
121
+ -H "X-API-Key: your-secret-key" \
122
+ -H "Content-Type: application/json" \
123
+ -d '{"jsonrpc": "2.0", ...}'
67
124
  ```
68
125
 
69
- ## Environment Variables
126
+ ### Scopes
70
127
 
71
- | Variable | Description | Default |
72
- |----------|-------------|---------|
73
- | `PROJECT_ROOT` | Path to project root | Current directory |
74
- | `AGENT_KIT_PATH` | Path to Agent Kit installation | Auto-detected |
128
+ | Scope | Tools Allowed |
129
+ |-------|---------------|
130
+ | `read:project` | get_project_context, get_project_intelligence |
131
+ | `read:graph` | analyze_dependencies, get_impact_zone |
132
+ | `read:search` | search_knowledge, search_code_logic |
133
+ | `write:sync` | force_sync |
134
+ | `admin:*` | All tools |
135
+
136
+ ## Observability
137
+
138
+ ### Metrics Endpoint
139
+
140
+ ```bash
141
+ # Get server metrics
142
+ curl http://localhost:3100/health
143
+
144
+ # Via MCP tool
145
+ mcp call get_metrics
146
+ ```
147
+
148
+ ### Trace Output
149
+
150
+ Traces are automatically exported to configured OTLP endpoint:
151
+
152
+ ```bash
153
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
154
+ ```
75
155
 
76
156
  ## Tools Reference
77
157
 
@@ -88,12 +168,11 @@ npm run build
88
168
  ```json
89
169
  {
90
170
  "file_path": "src/components/Button.tsx",
91
- "direction": "both", // "imports", "imported_by", "both"
92
- "depth": 2
171
+ "direction": "both" // "imports", "imported_by", "both"
93
172
  }
94
173
  ```
95
174
 
96
- ### search_code_logic
175
+ ### search_knowledge
97
176
 
98
177
  ```json
99
178
  {
@@ -107,8 +186,7 @@ npm run build
107
186
 
108
187
  ```json
109
188
  {
110
- "file_path": "src/utils/auth.ts",
111
- "depth": 3
189
+ "file_path": "src/utils/auth.ts"
112
190
  }
113
191
  ```
114
192
 
@@ -119,3 +197,74 @@ npm run build
119
197
  "target": "all" // or "graph", "rag", "agents_md"
120
198
  }
121
199
  ```
200
+
201
+ ### get_metrics
202
+
203
+ ```json
204
+ {}
205
+ ```
206
+
207
+ Returns:
208
+ ```json
209
+ {
210
+ "tools": {
211
+ "search_knowledge": {
212
+ "calls": 150,
213
+ "avgDuration": 320,
214
+ "p95Duration": 890,
215
+ "errorRate": 0.02
216
+ }
217
+ },
218
+ "summary": {
219
+ "totalRequests": 195,
220
+ "avgDuration": 280,
221
+ "uptime": 86400
222
+ }
223
+ }
224
+ ```
225
+
226
+ ### get_server_info
227
+
228
+ ```json
229
+ {}
230
+ ```
231
+
232
+ Returns server capabilities and version.
233
+
234
+ ## Architecture
235
+
236
+ ```
237
+ mcp-gateway/
238
+ ├── src/
239
+ │ ├── index.ts # Main entry point
240
+ │ ├── transports/
241
+ │ │ ├── index.ts
242
+ │ │ └── streamableHttp.ts # HTTP transport
243
+ │ ├── auth/
244
+ │ │ ├── index.ts
245
+ │ │ ├── oauth.ts # OAuth 2.1 implementation
246
+ │ │ ├── scopes.ts # Scope definitions
247
+ │ │ └── middleware.ts # Auth middleware
248
+ │ ├── observability/
249
+ │ │ ├── index.ts
250
+ │ │ └── otel.ts # OpenTelemetry integration
251
+ │ └── sync/
252
+ │ └── ... # Auto-sync modules
253
+ ├── dist/ # Compiled output
254
+ ├── package.json
255
+ └── README.md
256
+ ```
257
+
258
+ ## Upgrading from v1.x
259
+
260
+ 1. Update dependencies: `npm install`
261
+ 2. Rebuild: `npm run build`
262
+ 3. (Optional) Enable new features via env vars
263
+
264
+ No breaking changes to tool interfaces.
265
+
266
+ ---
267
+
268
+ **Version:** 2.0.0
269
+ **MCP SDK:** 1.12.0
270
+ **Node.js:** ≥20.0.0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@musashishao/agent-kit-mcp",
3
- "version": "1.0.0",
4
- "description": "MCP Gateway Server for Agent Kit - Live Project Cortex",
3
+ "version": "2.0.0",
4
+ "description": "MCP Gateway Server for Agent Kit - Enterprise-grade with OAuth 2.1, Streamable HTTP, and OpenTelemetry",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "bin": {
@@ -10,19 +10,34 @@
10
10
  "scripts": {
11
11
  "build": "tsc",
12
12
  "dev": "tsx src/index.ts",
13
+ "dev:http": "MCP_ENABLE_HTTP=true tsx src/index.ts",
13
14
  "start": "node dist/index.js",
14
- "watch": "tsc --watch"
15
+ "start:http": "MCP_ENABLE_HTTP=true node dist/index.js",
16
+ "watch": "tsc --watch",
17
+ "test": "node --test dist/**/*.test.js"
15
18
  },
16
19
  "dependencies": {
17
- "@modelcontextprotocol/sdk": "^1.0.0",
20
+ "@modelcontextprotocol/sdk": "^1.12.0",
18
21
  "zod": "^3.23.0"
19
22
  },
20
23
  "devDependencies": {
21
- "@types/node": "^20.0.0",
24
+ "@types/node": "^22.0.0",
22
25
  "tsx": "^4.0.0",
23
- "typescript": "^5.0.0"
26
+ "typescript": "^5.5.0"
24
27
  },
25
28
  "engines": {
26
- "node": ">=18.0.0"
29
+ "node": ">=20.0.0"
30
+ },
31
+ "keywords": [
32
+ "mcp",
33
+ "model-context-protocol",
34
+ "ai-agent",
35
+ "anthropic",
36
+ "claude",
37
+ "opentelemetry"
38
+ ],
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/ngotanthieu2000/agent-kit"
27
42
  }
28
43
  }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Auth module exports
3
+ */
4
+
5
+ // Re-export from oauth (excluding conflicting middleware exports)
6
+ export {
7
+ generatePKCE,
8
+ verifyPKCE,
9
+ generateAccessToken,
10
+ validateAccessToken,
11
+ revokeAccessToken,
12
+ generateAuthorizationCode,
13
+ exchangeAuthorizationCode,
14
+ hasScope,
15
+ hasAllScopes,
16
+ hasAnyScope,
17
+ extractBearerToken,
18
+ createApiKey,
19
+ validateApiKey,
20
+ extractApiKey,
21
+ MCP_SCOPES,
22
+ type OAuthConfig,
23
+ type TokenPayload,
24
+ type AuthResult,
25
+ type PKCEChallenge,
26
+ type MCPScope,
27
+ } from "./oauth.js";
28
+
29
+ // Re-export from scopes
30
+ export {
31
+ TOOL_SCOPES,
32
+ DEFAULT_SCOPES,
33
+ READ_ALL_SCOPES,
34
+ AGENT_SCOPES,
35
+ FULL_ACCESS_SCOPES,
36
+ getRequiredScopes,
37
+ hasToolAccess,
38
+ getScopeDescription,
39
+ isValidScope,
40
+ parseScopes,
41
+ serializeScopes,
42
+ getScopesForTools,
43
+ validateScopeRequest,
44
+ } from "./scopes.js";
45
+
46
+ // Re-export from middleware (with unique names)
47
+ export {
48
+ createAuthMiddleware,
49
+ authorizeToolCall,
50
+ requireToolAuth,
51
+ requireScopes,
52
+ type AuthMiddlewareConfig,
53
+ type AuthenticatedRequest,
54
+ } from "./middleware.js";
55
+
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Authentication Middleware for MCP Gateway
3
+ *
4
+ * Combines OAuth 2.1 and API Key authentication
5
+ * with flexible configuration.
6
+ */
7
+
8
+ import type { IncomingMessage, ServerResponse } from "http";
9
+ import { validateAccessToken, extractBearerToken, validateApiKey, extractApiKey, type AuthResult, type MCPScope } from "./oauth.js";
10
+ import { hasToolAccess, getRequiredScopes } from "./scopes.js";
11
+
12
+ // ============================================================================
13
+ // Types
14
+ // ============================================================================
15
+
16
+ export interface AuthMiddlewareConfig {
17
+ /** Enable authentication (default: true) */
18
+ enabled?: boolean;
19
+ /** Allow API key authentication */
20
+ allowApiKey?: boolean;
21
+ /** Allow bearer token authentication */
22
+ allowBearer?: boolean;
23
+ /** Paths that don't require authentication */
24
+ publicPaths?: string[];
25
+ /** Custom authentication handler */
26
+ customAuth?: (req: IncomingMessage) => Promise<AuthResult | null>;
27
+ }
28
+
29
+ export interface AuthenticatedRequest extends IncomingMessage {
30
+ auth?: AuthResult;
31
+ }
32
+
33
+ // ============================================================================
34
+ // Middleware Factory
35
+ // ============================================================================
36
+
37
+ /**
38
+ * Create authentication middleware
39
+ */
40
+ export function createAuthMiddleware(config: AuthMiddlewareConfig = {}) {
41
+ const {
42
+ enabled = true,
43
+ allowApiKey = true,
44
+ allowBearer = true,
45
+ publicPaths = ["/health", "/metrics"],
46
+ customAuth,
47
+ } = config;
48
+
49
+ return async function authMiddleware(
50
+ req: AuthenticatedRequest,
51
+ res: ServerResponse,
52
+ next: () => void
53
+ ): Promise<void> {
54
+ // Skip if auth disabled
55
+ if (!enabled) {
56
+ next();
57
+ return;
58
+ }
59
+
60
+ // Skip public paths
61
+ if (publicPaths.some(path => req.url?.startsWith(path))) {
62
+ next();
63
+ return;
64
+ }
65
+
66
+ let authResult: AuthResult | null = null;
67
+
68
+ // Try custom auth first
69
+ if (customAuth) {
70
+ authResult = await customAuth(req);
71
+ }
72
+
73
+ // Try Bearer token
74
+ if (!authResult && allowBearer) {
75
+ const token = extractBearerToken(req);
76
+ if (token) {
77
+ authResult = validateAccessToken(token);
78
+ }
79
+ }
80
+
81
+ // Try API key
82
+ if (!authResult && allowApiKey) {
83
+ const apiKey = extractApiKey(req);
84
+ if (apiKey) {
85
+ authResult = validateApiKey(apiKey);
86
+ }
87
+ }
88
+
89
+ // No credentials provided
90
+ if (!authResult) {
91
+ res.writeHead(401, {
92
+ "Content-Type": "application/json",
93
+ "WWW-Authenticate": 'Bearer realm="MCP Server", API-Key realm="MCP Server"',
94
+ });
95
+ res.end(JSON.stringify({
96
+ error: "authentication_required",
97
+ message: "Valid authentication credentials required",
98
+ }));
99
+ return;
100
+ }
101
+
102
+ // Invalid credentials
103
+ if (!authResult.valid) {
104
+ res.writeHead(401, {
105
+ "Content-Type": "application/json",
106
+ "WWW-Authenticate": `Bearer realm="MCP Server", error="${authResult.error}"`,
107
+ });
108
+ res.end(JSON.stringify({
109
+ error: "invalid_token",
110
+ message: authResult.error,
111
+ }));
112
+ return;
113
+ }
114
+
115
+ // Attach auth to request
116
+ req.auth = authResult;
117
+ next();
118
+ };
119
+ }
120
+
121
+ // ============================================================================
122
+ // Tool Authorization
123
+ // ============================================================================
124
+
125
+ /**
126
+ * Check if request is authorized for a specific tool
127
+ */
128
+ export function authorizeToolCall(
129
+ req: AuthenticatedRequest,
130
+ toolName: string
131
+ ): { authorized: boolean; error?: string } {
132
+ const auth = req.auth;
133
+
134
+ if (!auth || !auth.valid) {
135
+ return { authorized: false, error: "Not authenticated" };
136
+ }
137
+
138
+ if (!auth.scopes) {
139
+ return { authorized: false, error: "No scopes granted" };
140
+ }
141
+
142
+ if (!hasToolAccess(auth.scopes, toolName)) {
143
+ const required = getRequiredScopes(toolName);
144
+ return {
145
+ authorized: false,
146
+ error: `Insufficient scope. Required: ${required.join(", ")}`,
147
+ };
148
+ }
149
+
150
+ return { authorized: true };
151
+ }
152
+
153
+ /**
154
+ * Middleware to enforce scope for a specific tool
155
+ */
156
+ export function requireToolAuth(toolName: string) {
157
+ return function toolAuthMiddleware(
158
+ req: AuthenticatedRequest,
159
+ res: ServerResponse,
160
+ next: () => void
161
+ ): void {
162
+ const result = authorizeToolCall(req, toolName);
163
+
164
+ if (!result.authorized) {
165
+ res.writeHead(403, { "Content-Type": "application/json" });
166
+ res.end(JSON.stringify({
167
+ error: "insufficient_scope",
168
+ message: result.error,
169
+ tool: toolName,
170
+ required_scopes: getRequiredScopes(toolName),
171
+ }));
172
+ return;
173
+ }
174
+
175
+ next();
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Middleware to enforce specific scopes
181
+ */
182
+ export function requireScopes(...requiredScopes: MCPScope[]) {
183
+ return function scopeMiddleware(
184
+ req: AuthenticatedRequest,
185
+ res: ServerResponse,
186
+ next: () => void
187
+ ): void {
188
+ const auth = req.auth;
189
+
190
+ if (!auth || !auth.valid || !auth.scopes) {
191
+ res.writeHead(403, { "Content-Type": "application/json" });
192
+ res.end(JSON.stringify({
193
+ error: "insufficient_scope",
194
+ message: "Authentication required with appropriate scopes",
195
+ required_scopes: requiredScopes,
196
+ }));
197
+ return;
198
+ }
199
+
200
+ const missing = requiredScopes.filter(scope => {
201
+ // Admin wildcard
202
+ if (auth.scopes!.includes("admin:*")) return false;
203
+
204
+ // Direct match
205
+ if (auth.scopes!.includes(scope)) return false;
206
+
207
+ // Category wildcard
208
+ const [category] = scope.split(":");
209
+ if (auth.scopes!.includes(`${category}:*`)) return false;
210
+
211
+ return true;
212
+ });
213
+
214
+ if (missing.length > 0) {
215
+ res.writeHead(403, { "Content-Type": "application/json" });
216
+ res.end(JSON.stringify({
217
+ error: "insufficient_scope",
218
+ message: "Missing required scopes",
219
+ required_scopes: requiredScopes,
220
+ missing_scopes: missing,
221
+ granted_scopes: auth.scopes,
222
+ }));
223
+ return;
224
+ }
225
+
226
+ next();
227
+ };
228
+ }
229
+
230
+ // ============================================================================
231
+ // Utility Exports
232
+ // ============================================================================
233
+
234
+ export { AuthResult, MCPScope } from "./oauth.js";
235
+ export { hasToolAccess, getRequiredScopes, TOOL_SCOPES, DEFAULT_SCOPES, AGENT_SCOPES } from "./scopes.js";
236
+
237
+ export default {
238
+ createAuthMiddleware,
239
+ authorizeToolCall,
240
+ requireToolAuth,
241
+ requireScopes,
242
+ };