Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
ListToolsRequestSchema,
McpError,
} from '@modelcontextprotocol/sdk/types.js';
import type { ValidateFunction } from 'ajv';
import { type ActorCallOptions, ApifyApiError } from 'apify-client';

import log from '@apify/log';
Expand Down Expand Up @@ -45,6 +46,7 @@ export class ActorsMcpServer {
public readonly tools: Map<string, ToolEntry>;
private options: ActorsMcpServerOptions;
private toolsChangedHandler: ToolsChangedHandler | undefined;
private sigintHandler: (() => Promise<void>) | undefined;

constructor(options: ActorsMcpServerOptions = {}, setupSigintHandler = true) {
this.options = {
Expand Down Expand Up @@ -292,7 +294,6 @@ export class ActorsMcpServer {
public upsertTools(tools: ToolEntry[], shouldNotifyToolsChangedHandler = false) {
for (const wrap of tools) {
this.tools.set(wrap.tool.name, wrap);
log.info(`Added/updated tool: ${wrap.tool.name}`);
}
if (shouldNotifyToolsChangedHandler) this.notifyToolsChangedHandler();
return tools;
Expand All @@ -319,12 +320,13 @@ export class ActorsMcpServer {
this.server.onerror = (error) => {
console.error('[MCP Error]', error); // eslint-disable-line no-console
};
// Allow disabling of the SIGINT handler to prevent max listeners warning
if (setupSIGINTHandler) {
process.on('SIGINT', async () => {
const handler = async () => {
await this.server.close();
process.exit(0);
});
};
process.once('SIGINT', handler);
this.sigintHandler = handler; // Store the actual handler
}
}

Expand Down Expand Up @@ -497,6 +499,23 @@ export class ActorsMcpServer {
}

async close(): Promise<void> {
// Remove SIGINT handler
if (this.sigintHandler) {
process.removeListener('SIGINT', this.sigintHandler);
this.sigintHandler = undefined;
}
// Clear all tools and their compiled schemas
for (const tool of this.tools.values()) {
if (tool.tool.ajvValidate && typeof tool.tool.ajvValidate === 'function') {
(tool.tool as { ajvValidate: ValidateFunction<unknown> | null }).ajvValidate = null;
}
}
this.tools.clear();
// Unregister tools changed handler
if (this.toolsChangedHandler) {
this.unregisterToolsChangedHandler();
}
// Close server (which should also remove its event handlers)
await this.server.close();
}
}