Skip to main content
Glama

Context Pods

by conorluddy
index.tsโ€ข20.9 kB
/** * Context-Pods Core MCP Server * * This server manages other MCP servers in the Context-Pods toolkit. * It provides tools for creating, managing, and distributing MCP servers. */ import { logger } from '@context-pods/core'; import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js'; import { CONFIG } from './config/index.js'; import { getRegistryOperations } from './registry/index.js'; import { CreateMCPTool, WrapScriptTool, ListMCPsTool, ValidateMCPTool, AnalyzeCodebaseTool, } from './tools/index.js'; /** * Initialize tool instances */ const createMCPTool = new CreateMCPTool(); const wrapScriptTool = new WrapScriptTool(); const listMCPsTool = new ListMCPsTool(); const validateMCPTool = new ValidateMCPTool(); const analyzeCodebaseTool = new AnalyzeCodebaseTool(); /** * Create MCP server instance */ const server = new Server( { name: CONFIG.server.name, version: CONFIG.server.version, }, { capabilities: { tools: {}, resources: {}, }, }, ); /** * List available tools */ server.setRequestHandler(ListToolsRequestSchema, () => { return { tools: [ { name: 'create-mcp', description: `Generate a new MCP server from template with intelligent template selection. This tool creates a fully-functional MCP server with the specified configuration. The server name must follow specific naming conventions for compatibility. Format Requirements: - Name pattern: ^[a-zA-Z][a-zA-Z0-9_-]*$ (start with letter, then letters/numbers/hyphens/underscores) - Examples: "weather-api", "data_processor", "myTool123" - Invalid: "123server", "_server", "my server", "server@name" Language Selection: - typescript: Modern TypeScript with full type safety - javascript: Plain JavaScript with ES modules - python: Python 3.8+ with async/await support - rust: Rust with tokio async runtime - shell: POSIX shell script wrapper The tool automatically selects the best template based on your language preference, or you can specify a template directly for advanced customization.`, inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'Name of the MCP server to create (alphanumeric, hyphens, underscores)', pattern: '^[a-zA-Z][a-zA-Z0-9_-]*$', }, template: { type: 'string', description: 'Specific template to use (optional - will auto-select if not provided)', }, outputPath: { type: 'string', description: 'Output directory for the generated MCP server (optional)', }, description: { type: 'string', description: 'Description of the MCP server (optional)', }, language: { type: 'string', description: 'Preferred language (typescript, javascript, python, rust, shell)', enum: ['typescript', 'javascript', 'python', 'rust', 'shell'], }, variables: { type: 'object', description: 'Template variables for customization (optional)', additionalProperties: true, }, }, required: ['name'], }, }, { name: 'wrap-script', description: `Convert existing script to MCP server with automatic language detection. This tool wraps your existing scripts (Python, Shell, etc.) in a proper MCP server interface, enabling them to be used with MCP-compatible clients. Supported Script Types: - Python (.py): Detects Python scripts and creates async MCP wrapper - Shell (.sh, .bash): Creates shell command MCP interface - JavaScript (.js, .mjs): Wraps Node.js scripts with MCP protocol - TypeScript (.ts): Transpiles and wraps TypeScript scripts - Executable files: Creates generic command-line MCP wrapper Name Requirements: - Pattern: ^[a-zA-Z][a-zA-Z0-9_-]*$ (alphanumeric with hyphens/underscores) - Examples: "my_script_wrapper", "data-processor", "toolWrapper" - Invalid: "123wrapper", "_script", "my wrapper" The tool automatically detects the script language and selects the appropriate wrapper template, preserving your script's functionality while adding MCP compliance.`, inputSchema: { type: 'object', properties: { scriptPath: { type: 'string', description: 'Path to the script file to wrap', }, name: { type: 'string', description: 'Name for the generated MCP server', pattern: '^[a-zA-Z][a-zA-Z0-9_-]*$', }, template: { type: 'string', description: 'Specific template to use (optional - will auto-detect if not provided)', }, outputPath: { type: 'string', description: 'Output directory for the generated server (optional)', }, description: { type: 'string', description: 'Description of the wrapped server (optional)', }, variables: { type: 'object', description: 'Additional template variables (optional)', additionalProperties: true, }, }, required: ['scriptPath', 'name'], }, }, { name: 'list-mcps', description: `Show all managed MCP servers with filtering and formatting options. This tool provides comprehensive listing and filtering capabilities for all MCP servers managed by the Context-Pods toolkit. Filtering Options: - status: Filter by server status (created, building, ready, error, archived) - template: Filter by template name (basic, python-basic, typescript-advanced, etc.) - language: Filter by programming language (typescript, python, rust, shell, javascript) - search: Search in server names and descriptions (case-insensitive substring match) Output Formats: - table: Human-readable table format (default) - good for console viewing - json: Machine-readable JSON format - good for programmatic processing - summary: Condensed summary format - good for quick overviews Examples: - List all ready servers: {"status": "ready"} - Find Python servers: {"language": "python"} - Search for "weather": {"search": "weather"} - JSON format: {"format": "json"} The tool shows detailed information including status, template, language, build info, creation/update timestamps, and metadata for each managed server.`, inputSchema: { type: 'object', properties: { filter: { type: 'string', description: 'Legacy filter parameter (use specific filters instead)', }, status: { type: 'string', description: 'Filter by server status', enum: ['created', 'building', 'ready', 'error', 'archived'], }, template: { type: 'string', description: 'Filter by template name', }, language: { type: 'string', description: 'Filter by programming language', }, search: { type: 'string', description: 'Search in server names and descriptions', }, format: { type: 'string', description: 'Output format', enum: ['table', 'json', 'summary'], default: 'table', }, }, }, }, { name: 'validate-mcp', description: `Validate MCP server against official schema and best practices. This tool performs comprehensive validation of MCP servers to ensure they comply with MCP protocol standards and Context-Pods best practices. Validation Types: - Schema Validation (checkSchema: true): Validates against official MCP JSON schemas * Checks tool definitions, resource definitions, protocol compliance * Validates message formats and response structures * Ensures proper error handling patterns - Registry Validation (checkRegistry: true): Checks registration and metadata * Validates server registration in Context-Pods registry * Checks metadata completeness and accuracy * Verifies template compliance and configuration - Build Validation (checkBuild: false): Tests the build and runtime process * Attempts to build the server if applicable * Tests server startup and initialization * Validates runtime MCP communication Path Requirements: - Must be an absolute or relative path to the MCP server directory - Directory must contain valid MCP server files (package.json, main files, etc.) - Examples: "./my-server", "/path/to/server", "../generated/weather-api" The validation process provides detailed reports with specific errors, warnings, and suggestions for fixing any compliance issues found.`, inputSchema: { type: 'object', properties: { mcpPath: { type: 'string', description: 'Path to the MCP server directory to validate', }, checkRegistry: { type: 'boolean', description: 'Check registry status (default: true)', default: true, }, checkSchema: { type: 'boolean', description: 'Check MCP protocol compliance (default: true)', default: true, }, checkBuild: { type: 'boolean', description: 'Validate build process (default: false)', default: false, }, }, required: ['mcpPath'], }, }, { name: 'analyze-codebase', description: `Analyze codebase to identify functions suitable for MCP tool conversion. This tool scans source code files to identify functions that would make good MCP tools, providing scored opportunities with implementation guidance and template suggestions. Supported Languages: - TypeScript/JavaScript: Full AST analysis with type information - Python: AST-based function extraction and analysis (planned) - Rust/Go/Java: Pattern-based analysis with structure detection (planned) - Shell: Script and function pattern detection (planned) Analysis Features: - Function signature extraction and complexity scoring - API integration detection (HTTP clients, database calls) - Utility function identification (data transformation, validation) - Template matching with implementation guidance - Security and best practice recommendations Output Formats: - detailed: Comprehensive analysis with reasoning and recommendations - summary: Condensed overview of top opportunities - json: Machine-readable format for programmatic processing Example Usage: - Analyze TypeScript project: {"path": "./src", "languages": ["typescript"]} - Find high-value opportunities: {"path": "./src", "minScore": 80} - Quick summary: {"path": "./src", "outputFormat": "summary", "maxResults": 5}`, inputSchema: { type: 'object', properties: { path: { type: 'string', description: 'Path to codebase directory to analyze', }, languages: { type: 'array', items: { type: 'string' }, description: 'Specific languages to analyze (optional)', enum: ['typescript', 'javascript', 'python', 'rust', 'shell', 'go', 'java'], }, excludePatterns: { type: 'array', items: { type: 'string' }, description: 'Additional glob patterns to exclude from analysis', }, minScore: { type: 'number', description: 'Minimum opportunity score (0-100, default: 50)', minimum: 0, maximum: 100, default: 50, }, includeTests: { type: 'boolean', description: 'Include test files in analysis (default: false)', default: false, }, outputFormat: { type: 'string', enum: ['detailed', 'summary', 'json'], description: 'Output format (default: detailed)', default: 'detailed', }, maxResults: { type: 'number', description: 'Maximum number of opportunities to return (default: 10)', minimum: 1, maximum: 100, default: 10, }, }, required: ['path'], }, }, ], }; }); /** * Handle tool calls */ server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; try { switch (name) { case 'create-mcp': return await createMCPTool.safeExecute(args); case 'wrap-script': return await wrapScriptTool.safeExecute(args); case 'list-mcps': return await listMCPsTool.safeExecute(args); case 'validate-mcp': return await validateMCPTool.safeExecute(args); case 'analyze-codebase': return await analyzeCodebaseTool.safeExecute(args); default: throw new Error(`Unknown tool: ${name}`); } } catch (error) { logger.error(`Tool execution error: ${name}`, error); return { content: [ { type: 'text', text: `โŒ Internal error executing ${name}: ${error instanceof Error ? error.message : String(error)}`, }, ], }; } }); /** * List available resources */ server.setRequestHandler(ListResourcesRequestSchema, () => { return { resources: [ { uri: 'context-pods://mcps/', name: 'Managed MCP Servers', description: 'List of all managed MCP servers with metadata', mimeType: 'application/json', }, { uri: 'context-pods://templates/', name: 'Available Templates', description: 'List of available MCP server templates', mimeType: 'application/json', }, { uri: 'context-pods://status', name: 'System Status', description: 'Context-Pods system status and configuration', mimeType: 'application/json', }, { uri: 'context-pods://statistics', name: 'Server Statistics', description: 'Statistics about managed MCP servers', mimeType: 'application/json', }, ], }; }); /** * Read resource content */ server.setRequestHandler(ReadResourceRequestSchema, async (request) => { const { uri } = request.params; try { switch (uri) { case 'context-pods://mcps/': return await handleMCPsResource(); case 'context-pods://templates/': return await handleTemplatesResource(); case 'context-pods://status': return await handleStatusResource(); case 'context-pods://statistics': return await handleStatisticsResource(); default: throw new Error(`Unknown resource: ${uri}`); } } catch (error) { logger.error(`Resource error: ${uri}`, error); return { contents: [ { uri, mimeType: 'application/json', text: JSON.stringify( { error: `Failed to load resource: ${error instanceof Error ? error.message : String(error)}`, }, null, 2, ), }, ], }; } }); /** * Handle MCPs resource */ async function handleMCPsResource(): Promise<object> { const registry = await getRegistryOperations(); const servers = await registry.listServers(); return { contents: [ { uri: 'context-pods://mcps/', mimeType: 'application/json', text: JSON.stringify( { servers: servers.map((server) => ({ id: server.id, name: server.name, status: server.status, template: server.template, path: server.path, language: server.metadata.language, description: server.metadata.description, tags: server.metadata.tags, turboOptimized: server.metadata.turboOptimized, buildCommand: server.metadata.buildCommand, devCommand: server.metadata.devCommand, lastBuildStatus: server.metadata.lastBuildStatus, lastBuildTime: server.metadata.lastBuildTime, createdAt: server.createdAt, updatedAt: server.updatedAt, })), count: servers.length, lastUpdated: Date.now(), }, null, 2, ), }, ], }; } /** * Handle templates resource */ async function handleTemplatesResource(): Promise<object> { const { TemplateSelector } = await import('@context-pods/core'); const selector = new TemplateSelector(CONFIG.templatesPath); const templates = await selector.getAvailableTemplates(); return { contents: [ { uri: 'context-pods://templates/', mimeType: 'application/json', text: JSON.stringify( { templates: templates.map((t) => ({ name: t.template.name, language: t.template.language, description: t.template.description, tags: t.template.tags, optimization: t.template.optimization, variables: Object.keys(t.template.variables || {}), path: t.templatePath, })), count: templates.length, templatesPath: CONFIG.templatesPath, lastUpdated: Date.now(), }, null, 2, ), }, ], }; } /** * Handle status resource */ async function handleStatusResource(): Promise<object> { const registry = await getRegistryOperations(); const stats = await registry.getStatistics(); return { contents: [ { uri: 'context-pods://status', mimeType: 'application/json', text: JSON.stringify( { version: CONFIG.server.version, name: CONFIG.server.name, status: 'ready', configuration: { templatesPath: CONFIG.templatesPath, registryPath: CONFIG.registryPath, outputMode: CONFIG.outputMode, generatedPackagesPath: CONFIG.generatedPackagesPath, }, capabilities: { turboRepo: true, templateSelection: true, languageDetection: true, scriptWrapping: true, serverValidation: true, }, supportedLanguages: ['typescript', 'javascript', 'python', 'rust', 'shell'], serverCounts: stats.byStatus, uptime: process.uptime(), lastUpdated: Date.now(), }, null, 2, ), }, ], }; } /** * Handle statistics resource */ async function handleStatisticsResource(): Promise<object> { const registry = await getRegistryOperations(); const stats = await registry.getStatistics(); return { contents: [ { uri: 'context-pods://statistics', mimeType: 'application/json', text: JSON.stringify( { ...stats, lastUpdated: Date.now(), }, null, 2, ), }, ], }; } /** * Start the server */ async function main(): Promise<void> { try { // Initialize registry logger.info('Initializing Context-Pods registry...'); await getRegistryOperations(); // Start server const transport = new StdioServerTransport(); await server.connect(transport); logger.info('Context-Pods MCP server started successfully', { version: CONFIG.server.version, templatesPath: CONFIG.templatesPath, registryPath: CONFIG.registryPath, outputMode: CONFIG.outputMode, }); } catch (error) { logger.error('Failed to start Context-Pods server:', error); process.exit(1); } } /** * Handle graceful shutdown */ process.on('SIGINT', () => { logger.info('Shutting down Context-Pods server...'); process.exit(0); }); process.on('SIGTERM', () => { logger.info('Shutting down Context-Pods server...'); process.exit(0); }); // Start the server main().catch((error) => { logger.error('Server startup error:', error); process.exit(1); });

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/conorluddy/ContextPods'

If you have feedback or need assistance with the MCP directory API, please join our Discord server