actual-mcp-server 0.6.56 → 0.7.3

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 (37) hide show
  1. package/README.md +7 -7
  2. package/dist/package.json +4 -4
  3. package/dist/src/actualConnection.js +0 -2
  4. package/dist/src/actualToolsManager.js +1 -19
  5. package/dist/src/auth/setup.js +0 -4
  6. package/dist/src/index.js +1 -4
  7. package/dist/src/lib/ActualConnectionPool.js +0 -2
  8. package/dist/src/lib/ActualMCPConnection.js +0 -2
  9. package/dist/src/lib/actual-adapter.js +1 -28
  10. package/dist/src/lib/actual-schema.js +0 -9
  11. package/dist/src/lib/config-registry.js +1 -1
  12. package/dist/src/lib/constants.js +0 -43
  13. package/dist/src/lib/retry.js +0 -1
  14. package/dist/src/lib/toolFactory.js +0 -28
  15. package/dist/src/resources/accountsSummary.js +0 -2
  16. package/dist/src/server/httpServer.js +2 -2
  17. package/dist/src/tests/testMcpClient.js +5 -10
  18. package/dist/src/tests_adapter_runner.js +1 -1
  19. package/dist/src/tools/accounts_list.js +2 -1
  20. package/dist/src/tools/budget_updates_batch.js +0 -2
  21. package/dist/src/tools/budgets_getMonth.js +1 -0
  22. package/dist/src/tools/budgets_getMonths.js +1 -0
  23. package/dist/src/tools/categories_create.js +1 -0
  24. package/dist/src/tools/categories_get.js +1 -0
  25. package/dist/src/tools/category_groups_delete.js +0 -2
  26. package/dist/src/tools/category_groups_get.js +1 -1
  27. package/dist/src/tools/payees_get.js +1 -0
  28. package/dist/src/tools/rules_create_or_update.js +0 -2
  29. package/dist/src/tools/rules_delete.js +0 -2
  30. package/dist/src/tools/rules_get.js +1 -1
  31. package/dist/src/tools/schedules_delete.js +0 -2
  32. package/dist/src/tools/session_close.js +1 -1
  33. package/dist/src/utils.js +0 -51
  34. package/package.json +4 -4
  35. package/dist/src/lib/node-polyfills.js +0 -28
  36. package/dist/src/server/httpServer_testing.js +0 -401
  37. package/dist/src/server/streamable-http.js +0 -148
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "actual-mcp-server",
3
3
  "displayName": "Actual MCP Server",
4
- "version": "0.6.56",
4
+ "version": "0.7.3",
5
5
  "engines": {
6
- "node": ">=20.0.0",
6
+ "node": ">=22.0.0",
7
7
  "npm": ">=10.0.0"
8
8
  },
9
9
  "description": "MCP server with 71 tools for AI-driven financial management with Actual Budget. HTTP and stdio transports for LibreChat, Claude Desktop, Cursor, VS Code, Gemini CLI",
@@ -30,7 +30,7 @@
30
30
  "verify-tools": "npm run build && node scripts/verify-tools.js",
31
31
  "check:coverage": "node scripts/list-actual-api-methods.mjs",
32
32
  "direct-sync": "node scripts/direct-sync/bank-sync-direct.mjs",
33
- "test:unit-js": "node tests/unit/transactions_create.test.js && node tests/unit/generated_tools.smoke.test.js && node tests/unit/schema_validation.test.js && node tests/unit/config_https_validation.test.js && node tests/unit/config_data_dir.test.js && node tests/unit/config_drift.test.js && node tests/unit/port_alignment.test.js && node tests/unit/dockerfile_data_dir_alignment.test.js && node tests/unit/compose_profile_sync.test.js && node tests/unit/advertised_tools_sync.test.js && node tests/unit/knip_config.test.js && node tests/unit/node_polyfill_order.test.js && node tests/unit/config_insecure_upstream.test.js && node tests/unit/auth-acl.test.js && node tests/unit/bug76.test.js && node tests/unit/budgets_setAmount.test.js && node tests/unit/budgets_transfer.test.js && node tests/unit/transactions_uncategorized.test.js && node tests/unit/httpServer_session_init.test.js && node tests/unit/httpServer_session_not_found.test.js && node tests/unit/manual_mcp_client_retry.test.js && node tests/unit/manual_mcp_client_session.test.js && node tests/unit/manual_mcp_client_circuit.test.js && node tests/unit/manual_runner_killswitch.test.js && node tests/unit/adapter_auth_rate_limit.test.js && node tests/unit/adapter_session_reuse.test.js && node tests/unit/retry_classifier.test.js && node tests/unit/adapter_module_surface.test.js && node tests/unit/adapter_nonidempotent_no_retry.test.js && node tests/unit/pool_liveness.test.js && node tests/unit/pool_shutdown_all.test.js && node tests/unit/query_where_operators.test.js && node tests/unit/query_run_validation.test.js && node tests/unit/adapter_with_write_session.test.js && node tests/unit/category_groups_delete.test.js && node tests/unit/rules_delete.test.js && node tests/unit/schedules_delete.test.js && node tests/unit/payees_delete.test.js && node tests/unit/rules_create_or_update.test.js && node tests/unit/unhandled-rejection.test.js && node tests/unit/rejection-allowlist-purity.test.js && node tests/unit/httpServer_bearer_auth.test.js && node tests/unit/httpServer_oidc_audience.test.js && node tests/unit/httpServer_oidc_auth_verification.test.js && node tests/unit/httpServer_body_limit.test.js && node tests/unit/adapter_write_pool_cooperation.test.js && node tests/unit/budget_acl_enforcement.test.js && node tests/unit/budget_preference_store.test.js && node tests/unit/budget_preference_restore.test.js && node tests/unit/tags_list.test.js && node tests/unit/tags_create.test.js && node tests/unit/tags_update.test.js && node tests/unit/tags_delete.test.js && node tests/unit/notes_get.test.js && node tests/unit/notes_update.test.js && node tests/unit/payees_common_list.test.js && node tests/unit/transactions_update_guard.test.js && node tests/unit/entities_search.test.js && node tests/unit/transactions_import_schema.test.js && node tests/unit/tool_schema_shape.test.js && node tests/unit/zod_error_format.test.js && node tests/unit/tool_count_sync.test.js && node tests/unit/stdio_transport.test.js && node tests/unit/logger_structured.test.js && node tests/unit/logger_redaction.test.js && node tests/unit/logger_correlation.test.js && node tests/unit/check_coverage.test.js",
33
+ "test:unit-js": "node tests/unit/transactions_create.test.js && node tests/unit/generated_tools.smoke.test.js && node tests/unit/schema_validation.test.js && node tests/unit/config_https_validation.test.js && node tests/unit/config_data_dir.test.js && node tests/unit/config_drift.test.js && node tests/unit/port_alignment.test.js && node tests/unit/dockerfile_data_dir_alignment.test.js && node tests/unit/compose_profile_sync.test.js && node tests/unit/advertised_tools_sync.test.js && node tests/unit/knip_config.test.js && node tests/unit/readme_stats_sync.test.js && node tests/unit/config_insecure_upstream.test.js && node tests/unit/auth-acl.test.js && node tests/unit/bug76.test.js && node tests/unit/budgets_setAmount.test.js && node tests/unit/budgets_transfer.test.js && node tests/unit/transactions_uncategorized.test.js && node tests/unit/httpServer_session_init.test.js && node tests/unit/httpServer_session_not_found.test.js && node tests/unit/manual_mcp_client_retry.test.js && node tests/unit/manual_mcp_client_session.test.js && node tests/unit/manual_mcp_client_circuit.test.js && node tests/unit/manual_runner_killswitch.test.js && node tests/unit/adapter_auth_rate_limit.test.js && node tests/unit/adapter_session_reuse.test.js && node tests/unit/retry_classifier.test.js && node tests/unit/adapter_module_surface.test.js && node tests/unit/adapter_nonidempotent_no_retry.test.js && node tests/unit/pool_liveness.test.js && node tests/unit/pool_shutdown_all.test.js && node tests/unit/query_where_operators.test.js && node tests/unit/query_run_validation.test.js && node tests/unit/adapter_with_write_session.test.js && node tests/unit/category_groups_delete.test.js && node tests/unit/rules_delete.test.js && node tests/unit/schedules_delete.test.js && node tests/unit/payees_delete.test.js && node tests/unit/rules_create_or_update.test.js && node tests/unit/unhandled-rejection.test.js && node tests/unit/rejection-allowlist-purity.test.js && node tests/unit/httpServer_bearer_auth.test.js && node tests/unit/httpServer_oidc_audience.test.js && node tests/unit/httpServer_oidc_auth_verification.test.js && node tests/unit/httpServer_body_limit.test.js && node tests/unit/adapter_write_pool_cooperation.test.js && node tests/unit/budget_acl_enforcement.test.js && node tests/unit/budget_preference_store.test.js && node tests/unit/budget_preference_restore.test.js && node tests/unit/tags_list.test.js && node tests/unit/tags_create.test.js && node tests/unit/tags_update.test.js && node tests/unit/tags_delete.test.js && node tests/unit/notes_get.test.js && node tests/unit/notes_update.test.js && node tests/unit/payees_common_list.test.js && node tests/unit/transactions_update_guard.test.js && node tests/unit/entities_search.test.js && node tests/unit/transactions_import_schema.test.js && node tests/unit/tool_schema_shape.test.js && node tests/unit/zod_error_format.test.js && node tests/unit/tool_count_sync.test.js && node tests/unit/stdio_transport.test.js && node tests/unit/logger_structured.test.js && node tests/unit/logger_redaction.test.js && node tests/unit/logger_correlation.test.js && node tests/unit/check_coverage.test.js",
34
34
  "test:adapter": "npm run build && node dist/src/tests_adapter_runner.js",
35
35
  "test:e2e": "npx playwright test",
36
36
  "test:e2e:docker": "./tests/e2e/run-docker-e2e.sh",
@@ -57,7 +57,7 @@
57
57
  "release:patch": "npm run version:bump -- patch",
58
58
  "tool-count": "node scripts/tool-count.mjs",
59
59
  "config-drift": "npm run build && node scripts/config-drift.mjs",
60
- "knip": "knip --no-exit-code"
60
+ "knip": "knip"
61
61
  },
62
62
  "dependencies": {
63
63
  "@actual-app/api": "^26.6.0",
@@ -1,28 +0,0 @@
1
- /**
2
- * Node.js polyfills for browser globals required by @actual-app/api.
3
- *
4
- * @actual-app/api v26.3.0 introduced `navigator.platform` usage at the module
5
- * top level (inside the Electron/browser bundle) which crashes on Node.js with
6
- * `ReferenceError: navigator is not defined`. v26.6.0 additionally reads
7
- * `navigator.userAgent` at the top level (`navigator.userAgent.includes(...)`
8
- * plus a UAParser call), so the polyfill must define `userAgent` too or the
9
- * bundle throws `Cannot read properties of undefined (reading 'includes')`.
10
- *
11
- * Node 21+ ships a native `navigator` that already carries both fields, so this
12
- * polyfill only fires on Node 20 (still inside the documented "Node.js 20+"
13
- * support range, and the version several CI workflows run on).
14
- *
15
- * This file must be imported BEFORE any `@actual-app/api` import so that the
16
- * global is defined when the bundle is first evaluated.
17
- */
18
- if (typeof globalThis.navigator === 'undefined') {
19
- Object.defineProperty(globalThis, 'navigator', {
20
- value: {
21
- platform: process.platform === 'win32' ? 'Win32' : 'Linux',
22
- userAgent: `Node.js/${process.version}`,
23
- },
24
- writable: true,
25
- configurable: true,
26
- });
27
- }
28
- export {};
@@ -1,401 +0,0 @@
1
- import { z } from 'zod';
2
- import { randomUUID } from 'crypto';
3
- import express from 'express';
4
- import { Server } from './streamable-http.js';
5
- import { StreamableHTTPServerTransport } from './streamable-http.js';
6
- import { CallToolRequestSchema, ListToolsRequestSchema, } from './streamable-http.js';
7
- import logger from '../logger.js';
8
- // don't log at import time — only log when the server is actually started
9
- // console.error('Starting Streamable HTTP server...');
10
- // top-level logging removed so message is not printed at import-time
11
- // logger.info('Starting Streamable HTTP server (will be logged when startHttpServer is called)');
12
- export async function startHttpServer(mcp, port, httpPath) {
13
- logger.info('Starting Streamable HTTP server (testing)...');
14
- const app = express();
15
- app.use(express.json());
16
- // Map sessionId to transport
17
- const transports = new Map();
18
- // Tool schemas and types
19
- // ToolSchema isn't typed here; we'll cast request params at runtime below
20
- // Define tool schemas
21
- const HelloWorldSchema = z.object({
22
- name: z.string().describe("The name to greet")
23
- });
24
- const GetServerInfoSchema = z.object({});
25
- const LongRunningTestSchema = z.object({
26
- duration: z.number().optional().default(30).describe("Duration in seconds (default: 30)"),
27
- steps: z.number().optional().default(10).describe("Number of progress steps (default: 10)"),
28
- message: z.string().optional().describe("Optional message to include in the response")
29
- });
30
- const SlowTestSchema = z.object({
31
- message: z.string().optional().describe("Optional message to include in the response"),
32
- steps: z.number().optional().default(20).describe("Number of progress steps (default: 20)")
33
- });
34
- // Tool names enum
35
- let ToolName;
36
- (function (ToolName) {
37
- ToolName["HELLO_WORLD"] = "hello_world";
38
- ToolName["GET_SERVER_INFO"] = "get_server_info";
39
- ToolName["LONG_RUNNING_TEST"] = "long_running_test";
40
- ToolName["SLOW_TEST"] = "slow_test";
41
- })(ToolName || (ToolName = {}));
42
- // Function to create a new MCP server instance
43
- function createServerInstance() {
44
- const server = new Server({
45
- name: "simple-streamable-http-mcp-server",
46
- version: "1.0.0",
47
- }, {
48
- instructions: "A simple test MCP server implemented with Streamable HTTP transport. Supports basic tools and long-running operations with progress updates.",
49
- capabilities: {
50
- tools: {}
51
- }
52
- });
53
- // Set up the list tools handler
54
- server.setRequestHandler(ListToolsRequestSchema, async () => {
55
- logger.debug('[TOOLS LIST] Listing available tools');
56
- const tools = [
57
- {
58
- name: ToolName.HELLO_WORLD,
59
- description: "A simple tool that returns a greeting",
60
- inputSchema: z.toJSONSchema(HelloWorldSchema),
61
- },
62
- {
63
- name: ToolName.GET_SERVER_INFO,
64
- description: "Get information about the server",
65
- inputSchema: z.toJSONSchema(GetServerInfoSchema),
66
- },
67
- {
68
- name: ToolName.LONG_RUNNING_TEST,
69
- description: "A test tool that demonstrates long-running operations with progress updates",
70
- inputSchema: z.toJSONSchema(LongRunningTestSchema),
71
- },
72
- {
73
- name: ToolName.SLOW_TEST,
74
- description: "A test tool that takes 10 minutes to complete and returns timing information",
75
- inputSchema: z.toJSONSchema(SlowTestSchema),
76
- }
77
- ];
78
- return { tools };
79
- });
80
- // Set up the call tool handler
81
- server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
82
- const req = request;
83
- const params = req?.params ?? {};
84
- const name = params.name;
85
- const args = params.arguments;
86
- logger.debug(`[TOOL CALL] Tool: ${name}, Args: ${JSON.stringify(args, null, 2)}`);
87
- debug(`Tool request details: ${JSON.stringify(params, null, 2)}`);
88
- if (name === ToolName.HELLO_WORLD) {
89
- const validatedArgs = HelloWorldSchema.parse(args);
90
- debug(`hello_world tool called with args:`, validatedArgs);
91
- await new Promise(resolve => setTimeout(resolve, 200));
92
- return {
93
- content: [{
94
- type: "text",
95
- text: `Hello, ${validatedArgs.name}! Welcome to the MCP server.`
96
- }]
97
- };
98
- }
99
- if (name === ToolName.GET_SERVER_INFO) {
100
- debug(`get_server_info tool called`);
101
- return {
102
- content: [{
103
- type: "text",
104
- text: JSON.stringify({
105
- name: "Simple Streamable HTTP MCP Server",
106
- version: "1.0.0",
107
- features: ["tools"],
108
- timestamp: new Date().toISOString()
109
- }, null, 2)
110
- }]
111
- };
112
- }
113
- if (name === ToolName.LONG_RUNNING_TEST) {
114
- const validatedArgs = LongRunningTestSchema.parse(args);
115
- const { duration = 30, steps = 10, message } = validatedArgs;
116
- const startTime = new Date();
117
- const startTimestamp = startTime.toISOString();
118
- debug(`long_running_test started at: ${startTimestamp}, duration: ${duration}s, steps: ${steps}`);
119
- // Get progress token if available
120
- const progressToken = params['_meta'] ? params['_meta']?.progressToken : undefined;
121
- const stepDurationMs = (duration * 1000) / steps;
122
- // Send progress updates
123
- for (let i = 1; i <= steps; i++) {
124
- await new Promise(resolve => setTimeout(resolve, stepDurationMs));
125
- if (progressToken !== undefined) {
126
- try {
127
- logger.debug(`[PROGRESS] Sending progress update: ${i}/${steps} for token: ${progressToken}`);
128
- await server.notification({
129
- method: "notifications/progress",
130
- params: {
131
- progress: i,
132
- total: steps,
133
- progressToken,
134
- },
135
- }, { relatedRequestId: (extra && typeof extra === 'object' && 'requestId' in extra ? extra['requestId'] : undefined) });
136
- logger.debug(`[PROGRESS] Successfully sent progress update: ${i}/${steps}`);
137
- }
138
- catch (error) {
139
- logger.error(`[PROGRESS ERROR] Failed to send progress notification: ${String(error)}`);
140
- }
141
- }
142
- else {
143
- debug(`No progress token provided, skipping progress update ${i}/${steps}`);
144
- }
145
- }
146
- const endTime = new Date();
147
- const endTimestamp = endTime.toISOString();
148
- const actualDurationMs = endTime.getTime() - startTime.getTime();
149
- debug(`long_running_test completed at: ${endTimestamp}`);
150
- return {
151
- content: [{
152
- type: "text",
153
- text: JSON.stringify({
154
- message: message || "Long-running test completed successfully",
155
- start: startTimestamp,
156
- finish: endTimestamp,
157
- requestedDuration: duration,
158
- actualDuration: {
159
- milliseconds: actualDurationMs,
160
- seconds: actualDurationMs / 1000
161
- },
162
- steps: steps
163
- }, null, 2)
164
- }]
165
- };
166
- }
167
- if (name === ToolName.SLOW_TEST) {
168
- const validatedArgs = SlowTestSchema.parse(args);
169
- const { message, steps = 20 } = validatedArgs;
170
- const startTime = new Date();
171
- const startTimestamp = startTime.toISOString();
172
- debug(`slow_test tool started at: ${startTimestamp}`);
173
- // Get progress token if available
174
- const progressToken = params['_meta'] ? params['_meta']?.progressToken : undefined;
175
- // Wait for 10 minutes (600,000 milliseconds)
176
- const tenMinutesMs = 10 * 60 * 1000;
177
- const stepDurationMs = tenMinutesMs / steps;
178
- // Send progress updates
179
- for (let i = 1; i <= steps; i++) {
180
- await new Promise(resolve => setTimeout(resolve, stepDurationMs));
181
- if (progressToken !== undefined) {
182
- try {
183
- logger.debug(`[PROGRESS] Sending progress update: ${i}/${steps} for token: ${progressToken}`);
184
- await server.notification({
185
- method: "notifications/progress",
186
- params: {
187
- progress: i,
188
- total: steps,
189
- progressToken,
190
- },
191
- }, { relatedRequestId: (extra && typeof extra === 'object' && 'requestId' in extra ? extra['requestId'] : undefined) });
192
- logger.debug(`[PROGRESS] Successfully sent progress update: ${i}/${steps}`);
193
- }
194
- catch (error) {
195
- logger.error(`[PROGRESS ERROR] Failed to send progress notification: ${String(error)}`);
196
- }
197
- }
198
- else {
199
- debug(`No progress token provided, skipping progress update ${i}/${steps}`);
200
- }
201
- // Log progress every 5 steps
202
- if (i % 5 === 0) {
203
- const elapsedMinutes = (i / steps) * 10;
204
- logger.info(`[SLOW_TEST] Progress: ${i}/${steps} steps (${elapsedMinutes.toFixed(1)} minutes elapsed)`);
205
- }
206
- }
207
- const endTime = new Date();
208
- const endTimestamp = endTime.toISOString();
209
- const durationMs = endTime.getTime() - startTime.getTime();
210
- const durationMinutes = durationMs / (60 * 1000);
211
- debug(`slow_test tool completed at: ${endTimestamp}`);
212
- return {
213
- content: [{
214
- type: "text",
215
- text: JSON.stringify({
216
- message: message || "Slow test completed successfully",
217
- start: startTimestamp,
218
- finish: endTimestamp,
219
- duration: {
220
- milliseconds: durationMs,
221
- seconds: durationMs / 1000,
222
- minutes: durationMinutes
223
- },
224
- steps: steps
225
- }, null, 2)
226
- }]
227
- };
228
- }
229
- throw new Error(`Unknown tool: ${name}`);
230
- });
231
- return { server };
232
- }
233
- // Handle POST requests
234
- app.post(httpPath, async (req, res) => {
235
- logger.debug('Received MCP POST request');
236
- logger.debug('Request method: %s', req.body?.method);
237
- debug('Headers:', JSON.stringify(req.headers, null, 2));
238
- debug('Body:', JSON.stringify(req.body, null, 2));
239
- try {
240
- // Check for existing session ID
241
- const sessionId = req.headers['mcp-session-id'];
242
- let transport;
243
- if (sessionId && transports.has(sessionId)) {
244
- // Reuse existing transport
245
- transport = transports.get(sessionId);
246
- logger.debug(`[SESSION] Reusing existing transport for session ${sessionId}`);
247
- }
248
- else if (!sessionId) {
249
- // New initialization request
250
- logger.debug('[SESSION] Creating new server for initialization request');
251
- const { server } = createServerInstance();
252
- transport = new StreamableHTTPServerTransport({
253
- sessionIdGenerator: () => randomUUID(),
254
- enableJsonResponse: true,
255
- onsessioninitialized: (sessionId) => {
256
- transports.set(sessionId, transport);
257
- }
258
- });
259
- // Set up onclose handler to clean up transport when closed
260
- server.onclose = async () => {
261
- const sid = transport.sessionId;
262
- if (sid && transports.has(sid)) {
263
- transports.delete(sid);
264
- }
265
- };
266
- // Connect the transport to the MCP server BEFORE handling the request
267
- await server.connect(transport);
268
- await transport.handleRequest(req, res, req.body);
269
- return; // Already handled
270
- }
271
- else {
272
- // Invalid request - session ID provided but not found
273
- res.status(400).json({
274
- jsonrpc: '2.0',
275
- error: {
276
- code: -32000,
277
- message: 'Bad Request: Invalid session ID',
278
- },
279
- id: req?.body?.id,
280
- });
281
- return;
282
- }
283
- // Handle the request with existing transport
284
- await transport.handleRequest(req, res, req.body);
285
- }
286
- catch (error) {
287
- logger.error('Error handling MCP request: %s', String(error));
288
- if (!res.headersSent) {
289
- res.status(500).json({
290
- jsonrpc: '2.0',
291
- error: {
292
- code: -32603,
293
- message: 'Internal server error',
294
- },
295
- id: req?.body?.id,
296
- });
297
- }
298
- }
299
- });
300
- // Handle GET requests for SSE streams
301
- app.get(httpPath, async (req, res) => {
302
- logger.debug('Received MCP GET request');
303
- const sessionId = req.headers['mcp-session-id'];
304
- if (!sessionId || !transports.has(sessionId)) {
305
- res.status(400).json({
306
- jsonrpc: '2.0',
307
- error: {
308
- code: -32000,
309
- message: 'Bad Request: No valid session ID provided',
310
- },
311
- id: null,
312
- });
313
- return;
314
- }
315
- const lastEventId = req.headers['last-event-id'];
316
- if (lastEventId) {
317
- logger.debug(`Client reconnecting with Last-Event-ID: ${lastEventId}`);
318
- }
319
- else {
320
- logger.debug(`Establishing new SSE stream for session ${sessionId}`);
321
- }
322
- const transport = transports.get(sessionId);
323
- await transport.handleRequest(req, res);
324
- });
325
- // Handle DELETE requests for session termination
326
- app.delete(httpPath, async (req, res) => {
327
- const sessionId = req.headers['mcp-session-id'];
328
- if (!sessionId || !transports.has(sessionId)) {
329
- res.status(400).json({
330
- jsonrpc: '2.0',
331
- error: {
332
- code: -32000,
333
- message: 'Bad Request: No valid session ID provided',
334
- },
335
- id: null,
336
- });
337
- return;
338
- }
339
- logger.debug(`Received session termination request for session ${sessionId}`);
340
- try {
341
- const transport = transports.get(sessionId);
342
- await transport.handleRequest(req, res, req.body);
343
- }
344
- catch (error) {
345
- logger.error('Error handling session termination: %s', String(error));
346
- if (!res.headersSent) {
347
- res.status(500).json({
348
- jsonrpc: '2.0',
349
- error: {
350
- code: -32603,
351
- message: 'Error handling session termination',
352
- },
353
- id: null,
354
- });
355
- }
356
- }
357
- });
358
- // Health check endpoint
359
- app.get('/health', (req, res) => {
360
- res.json({
361
- status: 'ok',
362
- server: {
363
- name: "simple-streamable-http-mcp-server",
364
- version: "1.0.0"
365
- },
366
- transport: 'streamable-http',
367
- activeSessions: transports.size
368
- });
369
- });
370
- // Start server
371
- app.listen(port, () => {
372
- logger.info(`MCP Streamable HTTP Server listening on port ${port}`);
373
- logger.info(`📨 MCP endpoint: http://localhost:${port}${httpPath}`);
374
- logger.info(`❤️ Health check: http://localhost:${port}/health`);
375
- logger.info(`🛠️ Available tools: hello_world, get_server_info, long_running_test, slow_test`);
376
- });
377
- // Handle server shutdown
378
- process.on('SIGINT', async () => {
379
- logger.info('Shutting down server...');
380
- // Close all active transports
381
- for (const [sessionId, transport] of transports) {
382
- try {
383
- logger.debug(`Closing transport for session ${sessionId}`);
384
- await transport.close();
385
- transports.delete(sessionId);
386
- }
387
- catch (error) {
388
- logger.error(`Error closing transport for session ${sessionId}: ${String(error)}`);
389
- }
390
- }
391
- logger.info('Server shutdown complete');
392
- process.exit(0);
393
- });
394
- }
395
- const debug = (...args) => {
396
- if (process.env.DEBUG === 'true' || process.env.DEBUG === '1') {
397
- // safely stringify args to avoid implicit any spread
398
- const s = args.map(a => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ');
399
- console.debug('[DEBUG]', s);
400
- }
401
- };
@@ -1,148 +0,0 @@
1
- // Minimal TypeScript shim for the absent `streamable-http` package.
2
- // Implements only the surface used by src/server/httpServer.ts.
3
- import crypto from 'crypto';
4
- export const ListToolsRequestSchema = Symbol('ListToolsRequestSchema');
5
- export const CallToolRequestSchema = Symbol('CallToolRequestSchema');
6
- export const ToolSchema = {};
7
- export class Server {
8
- meta;
9
- options;
10
- handlers;
11
- transports;
12
- onclose;
13
- constructor(meta = {}, options = {}) {
14
- this.meta = meta;
15
- this.options = options;
16
- this.handlers = new Map();
17
- this.transports = new Set();
18
- }
19
- setRequestHandler(schema, handler) {
20
- this.handlers.set(schema, handler);
21
- }
22
- async connect(transport) {
23
- this.transports.add(transport);
24
- // Attach reference for test shims (loose typing intentionally preserved here)
25
- try {
26
- transport.server = this;
27
- }
28
- catch { }
29
- }
30
- async notification(payload, opts) {
31
- for (const t of this.transports) {
32
- if (typeof t.pushNotification === 'function') {
33
- try {
34
- await t.pushNotification(payload);
35
- }
36
- catch {
37
- // ignore
38
- }
39
- }
40
- }
41
- }
42
- // allow handlers to be invoked by transports (shim convenience)
43
- async invokeHandler(schema, req, extra) {
44
- const handler = this.handlers.get(schema);
45
- if (!handler)
46
- throw new Error('Handler not registered');
47
- return handler(req, extra);
48
- }
49
- }
50
- export class StreamableHTTPServerTransport {
51
- opts;
52
- sessionId;
53
- server;
54
- closed = false;
55
- constructor(opts = {}) {
56
- this.opts = opts;
57
- this.sessionId = null;
58
- this.server = null;
59
- }
60
- async pushNotification(_payload) {
61
- // noop
62
- }
63
- async handleRequest(req, res, bodyFromCaller) {
64
- const payload = (bodyFromCaller && Object.keys(bodyFromCaller).length ? bodyFromCaller : (req.body ?? {}));
65
- const method = payload.method;
66
- // Always include session ID in response headers if we have one
67
- if (this.sessionId) {
68
- res.setHeader('MCP-Session-Id', this.sessionId);
69
- }
70
- if (method === 'initialize') {
71
- this.sessionId =
72
- typeof this.opts.sessionIdGenerator === 'function'
73
- ? this.opts.sessionIdGenerator()
74
- : crypto.randomUUID?.() ?? `local-${Math.random().toString(36).slice(2, 10)}`;
75
- if (typeof this.opts.onsessioninitialized === 'function') {
76
- try {
77
- this.opts.onsessioninitialized(this.sessionId);
78
- }
79
- catch { }
80
- }
81
- // Provide a robust initialize result with safe defaults so MCP clients
82
- // that validate serverInstructions / capabilities / tools won't error.
83
- const result = {
84
- protocolVersion: '2025-06-18',
85
- identifier: 'actual-mcp-server',
86
- // capabilities expected to be an object like { tools: { ... } }
87
- capabilities: this.server?.options?.capabilities ?? { tools: {} },
88
- // some clients expect serverInstructions to exist (object or string)
89
- serverInstructions: this.server?.options?.serverInstructions ?? '',
90
- // advertise known tools when available
91
- tools: this.server?.options?.implementedTools ?? [],
92
- };
93
- // Set the MCP-Session-Id header so clients can make subsequent requests
94
- res.setHeader('MCP-Session-Id', this.sessionId);
95
- res.json({ jsonrpc: '2.0', id: payload.id ?? null, result });
96
- return;
97
- }
98
- if (method === 'tools/list') {
99
- if (!this.server) {
100
- res.status(500).json({ jsonrpc: '2.0', id: payload.id ?? null, error: { message: 'Server not connected' } });
101
- return;
102
- }
103
- try {
104
- const r = await this.server.invokeHandler(ListToolsRequestSchema, { params: {} });
105
- res.json({ jsonrpc: '2.0', id: payload.id ?? null, result: r });
106
- return;
107
- }
108
- catch (e) {
109
- res.status(500).json({ jsonrpc: '2.0', id: payload.id ?? null, error: { message: String(e) } });
110
- return;
111
- }
112
- }
113
- if (method === 'tools/call' && payload.params && payload.params.name) {
114
- if (!this.server) {
115
- res.status(500).json({ jsonrpc: '2.0', id: payload.id ?? null, error: { message: 'Server not connected' } });
116
- return;
117
- }
118
- try {
119
- const params = payload.params;
120
- const r = await this.server.invokeHandler(CallToolRequestSchema, { params: { name: params.name, arguments: params.arguments ?? {} } }, {});
121
- res.json({ jsonrpc: '2.0', id: payload.id ?? null, result: r });
122
- return;
123
- }
124
- catch (e) {
125
- res.status(500).json({ jsonrpc: '2.0', id: payload.id ?? null, error: { message: String(e) } });
126
- return;
127
- }
128
- }
129
- if (method === 'ping') {
130
- if (payload.id !== undefined)
131
- res.json({ jsonrpc: '2.0', id: payload.id, result: {} });
132
- else
133
- res.status(200).end();
134
- return;
135
- }
136
- if (typeof method === 'string' && method.startsWith('notifications/')) {
137
- res.status(200).end();
138
- return;
139
- }
140
- res.status(404).json({ jsonrpc: '2.0', id: payload.id ?? null, error: { code: -32601, message: 'Method not found' } });
141
- }
142
- async close() {
143
- this.closed = true;
144
- if (this.server && typeof this.server.removeTransport === 'function') {
145
- this.server.removeTransport(this);
146
- }
147
- }
148
- }