import {
CallToolRequestSchema,
ListToolsRequestSchema,
ListResourcesRequestSchema,
ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { ToolRegistry } from '../tools/registry.js';
import { ResourceRegistry } from '../resources/registry.js';
export class RequestHandlers {
constructor(
private server: Server,
private toolRegistry: ToolRegistry,
private resourceRegistry: ResourceRegistry
) {
this.setupHandlers();
}
private setupHandlers() {
this.setupToolHandlers();
this.setupResourceHandlers();
}
private setupToolHandlers() {
// Handle tool listing
this.server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: this.toolRegistry.getAllTools(),
};
});
// Handle tool calls
this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
if (!args) {
throw new Error('Arguments are required');
}
const tool = this.toolRegistry.getTool(name);
if (!tool) {
throw new Error(`Unknown tool: ${name}`);
}
const result = await tool.execute(args);
return {
content: result.content,
isError: result.isError || false,
};
});
}
private setupResourceHandlers() {
// Handle resource listing
this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: this.resourceRegistry.getAllResources(),
};
});
// Handle resource reading
this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const { uri } = request.params;
const resource = this.resourceRegistry.getResource(uri);
if (!resource) {
throw new Error(`Unknown resource: ${uri}`);
}
const content = await resource.read(uri);
return {
contents: [content],
};
});
}
}