import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { CallToolResult, GetPromptResult, ReadResourceResult } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; //#region src/types/index.d.ts /** * Tool definition for MCP * @property name - The unique name of the tool * @property description - Human-readable description of what the tool does * @property inputSchema - JSON Schema defining the tool's input parameters */ interface ToolDefinition { name: string; description: string; inputSchema: { type: string; properties: Record; required?: string[]; additionalProperties?: boolean; }; _meta?: Record; } /** * Base tool interface following MCP SDK patterns * @template TInput - The type of input the tool accepts */ interface Tool { getDefinition(): ToolDefinition | Promise; execute(input: TInput): Promise; } /** * Transport mode constants */ declare const TRANSPORT_MODE: { readonly STDIO: "stdio"; readonly HTTP: "http"; readonly SSE: "sse"; }; /** * Transport mode type derived from TRANSPORT_MODE constants */ type TransportMode = (typeof TRANSPORT_MODE)[keyof typeof TRANSPORT_MODE]; /** * Transport configuration options * @property mode - The transport mode to use (stdio, http, or sse) * @property port - Port number for HTTP/SSE modes (not used for STDIO) * @property host - Host address for HTTP/SSE modes (not used for STDIO) */ interface TransportConfig { mode: TransportMode; port?: number; host?: string; } /** * Base interface for all transport handlers */ interface TransportHandler { start(): Promise; stop(): Promise; } /** * HTTP transport specific types */ interface HttpTransportHandler$1 extends TransportHandler { getPort(): number; getHost(): string; } /** * Runtime state persisted for HTTP one-mcp instances. * @property serverId - Unique one-mcp server identifier * @property host - Host bound by the HTTP transport * @property port - Port bound by the HTTP transport * @property transport - Transport mode for the runtime record * @property shutdownToken - Secret token required for admin shutdown requests * @property startedAt - ISO timestamp when the runtime started * @property pid - Process ID of the running one-mcp process * @property configPath - Optional path to the config file used to start the server */ interface RuntimeStateRecord { serverId: string; host: string; port: number; transport: 'http'; shutdownToken: string; startedAt: string; pid: number; configPath?: string; } /** * Optional admin settings for HTTP transport lifecycle actions. * @property serverId - Server identifier surfaced via health responses * @property shutdownToken - Secret token accepted by the admin shutdown endpoint * @property onShutdownRequested - Callback invoked after a valid shutdown request is received */ interface HttpTransportAdminOptions { serverId?: string; shutdownToken?: string; onShutdownRequested?: () => Promise; } /** * Health payload exposed by HTTP transport. * @property status - Health status string for liveness checks * @property transport - Transport mode for the serving endpoint * @property serverId - Optional server identifier for target verification */ interface HttpTransportHealthResponse { status: 'ok'; transport: 'http'; serverId?: string; } /** * Admin shutdown response payload. * @property ok - Whether shutdown request handling succeeded * @property message - Human-readable outcome message * @property serverId - Optional server identifier associated with this response */ interface HttpTransportShutdownResponse { ok: boolean; message: string; serverId?: string; } /** * Runtime record lookup filters. * @property host - Optional host filter for runtime discovery * @property port - Optional port filter for runtime discovery */ interface RuntimeLookupOptions { host?: string; port?: number; } /** * Runtime service contract. */ interface RuntimeStateManager { /** * Persist a runtime state record. * @param record - Runtime metadata to persist * @returns Promise that resolves when write completes */ write(record: RuntimeStateRecord): Promise; /** * Read a runtime state record by server ID. * @param serverId - Target one-mcp server identifier * @returns Matching runtime record, or null when no record exists */ read(serverId: string): Promise; /** * List all persisted runtime records. * @returns Array of runtime records */ list(): Promise; /** * Remove a runtime state record by server ID. * @param serverId - Target one-mcp server identifier * @returns Promise that resolves when delete completes */ remove(serverId: string): Promise; } /** * Remote MCP server configuration types */ type McpServerTransportType = 'stdio' | 'http' | 'sse'; /** * Configuration for stdio-based MCP server connections * @property command - The command to execute to start the server * @property args - Optional arguments to pass to the command * @property env - Optional environment variables for the subprocess */ interface McpStdioConfig { command: string; args?: string[]; env?: Record; } /** * Configuration for HTTP-based MCP server connections * @property url - The URL of the HTTP endpoint * @property headers - Optional HTTP headers to include in requests */ interface McpHttpConfig { url: string; headers?: Record; } /** * Configuration for SSE-based MCP server connections * @property url - The URL of the SSE endpoint * @property headers - Optional HTTP headers to include in requests */ interface McpSseConfig { url: string; headers?: Record; } /** * Union type for MCP server transport configurations * - McpStdioConfig: Used for local subprocess communication via stdio (has 'command' property) * - McpHttpConfig: Used for HTTP-based remote connections (has 'url' property) * - McpSseConfig: Used for Server-Sent Events streaming connections (has 'url' property) * * Note: McpHttpConfig and McpSseConfig have identical structure. Discrimination between * them should be done using the transport type field in McpServerConfig, not by * structural inspection of the config object. */ type McpServerTransportConfig = McpStdioConfig | McpHttpConfig | McpSseConfig; /** * Configuration for an MCP server connection * @property name - Unique identifier for the server * @property instruction - Optional instruction text describing the server's purpose * @property toolBlacklist - Optional list of tool names to exclude from this server * @property omitToolDescription - Whether to omit tool descriptions in listings * @property prompts - Optional prompts configuration for skill conversion * @property transport - The transport type (stdio, http, or sse) * @property config - Transport-specific configuration options * @property timeout - Optional connection timeout in milliseconds (default: 30000) * @property disabled - Whether this server is disabled and should not be started */ interface McpServerConfig { name: string; instruction?: string; toolBlacklist?: string[]; omitToolDescription?: boolean; prompts?: Record; transport: McpServerTransportType; config: McpServerTransportConfig; timeout?: number; /** Optional per-request timeout in milliseconds for tool calls (default: 60000 from MCP SDK) */ requestTimeout?: number; disabled?: boolean; } /** * Skills configuration * @property paths - Array of paths to skills directories */ interface SkillsConfig { paths: string[]; } /** * Prompt skill configuration for converting prompts to executable skills * @property name - Skill name identifier * @property description - Skill description shown in describe_tools * @property folder - Optional folder path for skill resources */ interface PromptSkillConfig { name: string; description: string; folder?: string; } /** * Prompt configuration that can be converted to a skill * @property skill - Optional skill conversion configuration */ interface PromptConfig { skill?: PromptSkillConfig; } /** * Remote configuration response containing MCP server definitions * @property id - Optional unique server identifier * @property mcpServers - Map of server names to their configurations * @property skills - Optional skills configuration with paths */ interface RemoteMcpConfiguration { id?: string; mcpServers: Record; skills?: SkillsConfig; } /** * MCP tool information returned from listTools * @property name - The tool name * @property description - Human-readable description * @property inputSchema - JSON Schema for tool inputs */ interface McpToolInfo { name: string; description?: string; inputSchema: Record; _meta?: Record; } /** * MCP resource information returned from listResources * @property uri - Resource URI * @property name - Display name * @property description - Human-readable description * @property mimeType - Optional MIME type */ interface McpResourceInfo { uri: string; name?: string; description?: string; mimeType?: string; } /** * MCP prompt information returned from listPrompts * @property name - Prompt name * @property description - Human-readable description * @property arguments - Optional argument definitions */ interface McpPromptInfo { name: string; description?: string; arguments?: Array<{ name: string; description?: string; required?: boolean; }>; } /** * MCP client connection interface for communicating with remote MCP servers * @property serverName - The name identifier for this server connection * @property serverInstruction - Optional instruction text for the server * @property toolBlacklist - Optional list of tool names to exclude * @property omitToolDescription - Whether to omit tool descriptions * @property prompts - Optional prompts configuration for skill conversion * @property transport - The transport type used for this connection */ interface McpClientConnection { serverName: string; serverInstruction?: string; toolBlacklist?: string[]; omitToolDescription?: boolean; prompts?: Record; transport: McpServerTransportType; /** List available tools from the server */ listTools(): Promise; /** List available resources from the server */ listResources(): Promise; /** List available prompts from the server */ listPrompts(): Promise; /** Call a tool with the given name and arguments */ callTool(name: string, args: Record, options?: { timeout?: number; }): Promise; /** Read a resource by URI */ readResource(uri: string): Promise; /** Get a prompt by name with optional arguments */ getPrompt(name: string, args?: Record): Promise; /** Close the connection */ close(): Promise; } /** * Cached prompt-based skill metadata. * Used to avoid re-fetching prompt front matter during startup discovery. */ interface CachedPromptSkillInfo { promptName: string; skill: PromptSkillConfig; autoDetected?: boolean; } /** * Cached server metadata used for startup-time capability discovery. */ interface CachedServerDefinition { serverName: string; serverInstruction?: string; omitToolDescription?: boolean; toolBlacklist?: string[]; tools: McpToolInfo[]; resources: McpResourceInfo[]; prompts: McpPromptInfo[]; promptSkills: CachedPromptSkillInfo[]; } /** * Cached file-based skill metadata. */ interface CachedFileSkillInfo { name: string; description: string; location: 'project' | 'user'; basePath: string; } /** * Cache file storing precomputed definitions for one-mcp startup. */ interface DefinitionsCacheFile { version: 1; oneMcpVersion?: string; generatedAt: string; configPath?: string; configHash?: string; serverId?: string; servers: Record; skills: CachedFileSkillInfo[]; failures: Array<{ serverName: string; error: string; }>; } /** * Skill metadata from YAML frontmatter in SKILL.md files * @property name - Skill identifier used with skill__ prefix * @property description - Short description shown in describe_tools * @property license - Optional license information */ interface SkillMetadata { name: string; description: string; license?: string; } /** * Skill definition loaded from skill files * @property name - Skill identifier used with skill__ prefix * @property description - Short description shown in describe_tools * @property location - Where the skill was loaded from ('project' or 'user') * @property content - The markdown content of the skill (without frontmatter) * @property basePath - The directory path where the skill is located */ interface Skill { name: string; description: string; location: 'project' | 'user'; content: string; basePath: string; } //#endregion //#region src/services/SkillService.d.ts /** * Service for loading and managing skills from configured skill directories. * * Skills are markdown files with YAML frontmatter that can be invoked via * the skill__ prefix in describe_tools and use_tool. * * Skills are only enabled when explicitly configured via the `skills.paths` array * in the MCP config. * * @example * // Config with skills enabled: * // skills: * // paths: * // - ".claude/skills" * // - "/absolute/path/to/skills" * * const skillService = new SkillService('/project/root', ['.claude/skills']); * const skills = await skillService.getSkills(); */ declare class SkillService { private cwd; private skillPaths; private cachedSkills; private skillsByName; /** Active file watchers for skill directories */ private watchers; /** Polling timers used when native file watching is unavailable */ private pollingTimers; /** Callback invoked when cache is invalidated due to file changes */ private onCacheInvalidated?; /** * Creates a new SkillService instance * @param cwd - Current working directory for resolving relative paths * @param skillPaths - Array of paths to skills directories * @param options - Optional configuration * @param options.onCacheInvalidated - Callback invoked when cache is invalidated due to file changes */ constructor(cwd: string, skillPaths: string[], options?: { onCacheInvalidated?: () => void; }); /** * Get all available skills from configured directories. * Results are cached after first load. * * Skills from earlier entries in the config take precedence over * skills with the same name from later entries. * * @returns Array of loaded skills * @throws SkillLoadError if a critical error occurs during loading */ getSkills(): Promise; /** * Get a specific skill by name with O(1) lookup from cache. * @param name - The skill name (without skill__ prefix) * @returns The skill if found, undefined otherwise */ getSkill(name: string): Promise; /** * Clears the cached skills to force a fresh reload on the next getSkills() or getSkill() call. * Use this when skill files have been modified on disk. */ clearCache(): void; /** * Starts watching skill directories for changes to SKILL.md files. * When changes are detected, the cache is automatically invalidated. * * Uses Node.js fs.watch with recursive option for efficient directory monitoring. * Only invalidates cache when SKILL.md files are modified. * * @example * const skillService = new SkillService(cwd, skillPaths, { * onCacheInvalidated: () => console.log('Skills cache invalidated') * }); * await skillService.startWatching(); */ startWatching(): Promise; /** * Stops all active file watchers. * Should be called when the service is being disposed. */ stopWatching(): void; /** * Watches a directory for changes to SKILL.md files. * @param dirPath - Directory path to watch * @param signal - AbortSignal to stop watching */ private watchDirectory; private invalidateCache; private isWatchResourceLimitError; private startPollingDirectory; private createSkillSnapshot; private collectSkillSnapshots; private snapshotsEqual; /** * Load skills from a directory. * Supports both flat structure (SKILL.md) and nested structure (name/SKILL.md). * * @param dirPath - Path to the skills directory * @param location - Whether this is a 'project' or 'user' skill directory * @returns Array of successfully loaded skills (skips invalid skills) * @throws SkillLoadError if there's a critical I/O error * * @example * // Load skills from project directory * const skills = await this.loadSkillsFromDirectory('/path/to/.claude/skills', 'project'); * // Returns: [{ name: 'pdf', description: '...', location: 'project', ... }] */ private loadSkillsFromDirectory; /** * Load a single skill file and parse its frontmatter. * Supports multi-line YAML values using literal (|) and folded (>) block scalars. * * @param filePath - Path to the SKILL.md file * @param location - Whether this is a 'project' or 'user' skill * @returns The loaded skill, or null if the file is invalid (missing required frontmatter) * @throws SkillLoadError if there's an I/O error reading the file * * @example * // Load a skill from a file * const skill = await this.loadSkillFile('/path/to/pdf/SKILL.md', 'project'); * // Returns: { name: 'pdf', description: 'PDF skill', location: 'project', content: '...', basePath: '/path/to/pdf' } * // Returns null if frontmatter is missing name or description */ private loadSkillFile; } //#endregion //#region src/services/McpClientManagerService.d.ts /** * Service for managing MCP client connections to remote servers */ declare class McpClientManagerService { private clients; private serverConfigs; private connectionPromises; /** * Synchronously kill all stdio MCP server child processes. * Must be called by the owner (e.g. transport/command layer) during shutdown. */ cleanupChildProcesses(): void; /** * Connect to an MCP server based on its configuration with timeout * Uses the timeout from server config, falling back to default (30s) */ connectToServer(serverName: string, config: McpServerConfig): Promise; registerServerConfigs(configs: Record): void; getKnownServerNames(): string[]; getServerRequestTimeout(serverName: string): number | undefined; ensureConnected(serverName: string): Promise; private createConnection; /** * Perform the actual connection to MCP server */ private performConnection; private connectStdioClient; private connectHttpClient; private connectSseClient; /** * Get a connected client by server name */ getClient(serverName: string): McpClientConnection | undefined; /** * Get all connected clients */ getAllClients(): McpClientConnection[]; /** * Disconnect from a specific server */ disconnectServer(serverName: string): Promise; /** * Disconnect from all servers */ disconnectAll(): Promise; /** * Check if a server is connected */ isConnected(serverName: string): boolean; } //#endregion //#region src/services/DefinitionsCacheService.d.ts interface DefinitionsCacheServiceOptions { cacheData?: DefinitionsCacheFile; } interface PromptSkillMatch { serverName: string; promptName: string; skill: PromptSkillConfig; autoDetected?: boolean; } interface CollectOptions { serverId?: string; configPath?: string; configHash?: string; oneMcpVersion?: string; } declare class DefinitionsCacheService { private clientManager; private skillService?; private cacheData?; private liveDefinitionsPromise; private mergedDefinitionsPromise; constructor(clientManager: McpClientManagerService, skillService?: SkillService, options?: DefinitionsCacheServiceOptions); static readFromFile(filePath: string): Promise; static writeToFile(filePath: string, cache: DefinitionsCacheFile): Promise; static getDefaultCachePath(configFilePath: string): string; static generateConfigHash(config: unknown): string; static isCacheValid(cache: DefinitionsCacheFile, options: { configHash?: string; oneMcpVersion?: string; }): boolean; static clearFile(filePath: string): Promise; clearLiveCache(): void; setCacheData(cacheData?: DefinitionsCacheFile): void; collectForCache(options?: CollectOptions): Promise; getDefinitions(): Promise; getServerDefinitions(): Promise; getServersForTool(toolName: string): Promise; getServersForResource(uri: string): Promise; getPromptSkillByName(skillName: string): Promise; getCachedFileSkills(): Promise; private getLiveDefinitions; private collectLiveDefinitions; private collectFileSkills; private toCachedFileSkill; private listPromptsSafe; private listResourcesSafe; private collectPromptSkillsForClient; } //#endregion //#region src/tools/DescribeToolsTool.d.ts /** * Input schema for the DescribeToolsTool * @property toolNames - Array of tool names to get detailed information about */ interface DescribeToolsToolInput { toolNames: string[]; } /** * DescribeToolsTool provides progressive disclosure of MCP tools and skills. * * This tool lists available tools from all connected MCP servers and skills * from the configured skills directories. Users can query for specific tools * or skills to get detailed input schemas and descriptions. * * Tool naming conventions: * - Unique tools: use plain name (e.g., "browser_click") * - Clashing tools: use serverName__toolName format (e.g., "playwright__click") * - Skills: use skill__skillName format (e.g., "skill__pdf") * * @example * const tool = new DescribeToolsTool(clientManager, skillService); * const definition = await tool.getDefinition(); * const result = await tool.execute({ toolNames: ['browser_click', 'skill__pdf'] }); */ declare class DescribeToolsTool implements Tool { static readonly TOOL_NAME = "describe_tools"; private clientManager; private skillService; private definitionsCacheService; private readonly liquid; /** Cache for auto-detected skills from prompt front-matter */ private autoDetectedSkillsCache; /** Unique server identifier for this one-mcp instance */ private serverId; /** * Creates a new DescribeToolsTool instance * @param clientManager - The MCP client manager for accessing remote servers * @param skillService - Optional skill service for loading skills * @param serverId - Unique server identifier for this one-mcp instance */ constructor(clientManager: McpClientManagerService, skillService?: SkillService, serverId?: string, definitionsCacheService?: DefinitionsCacheService); /** * Clears the cached auto-detected skills from prompt front-matter. * Use this when prompt configurations may have changed or when * the skill service cache is invalidated. */ clearAutoDetectedSkillsCache(): void; /** * Detects and caches skills from prompt front-matter across all connected MCP servers. * Fetches all prompts and checks their content for YAML front-matter with name/description. * Results are cached to avoid repeated fetches. * * Error Handling Strategy: * - Errors are logged to stderr but do not fail the overall detection process * - This ensures partial results are returned even if some servers/prompts fail * - Common failure reasons: server temporarily unavailable, prompt requires arguments, * network timeout, or server doesn't support listPrompts * - Errors are prefixed with [skill-detection] for easy filtering in logs * * @returns Array of auto-detected skills from prompt front-matter */ private detectSkillsFromPromptFrontMatter; /** * Collects skills derived from prompt configurations across all connected MCP servers. * Includes both explicitly configured prompts and auto-detected skills from front-matter. * * @returns Array of skill template data derived from prompts */ private collectPromptSkills; /** * Finds a prompt-based skill by name from all connected MCP servers. * Searches both explicitly configured prompts and auto-detected skills from front-matter. * * @param skillName - The skill name to search for * @returns Object with serverName, promptName, and skill config, or undefined if not found */ private findPromptSkill; /** * Retrieves skill content from a prompt-based skill configuration. * Fetches the prompt from the MCP server and extracts text content. * Handles both explicitly configured prompts and auto-detected skills from front-matter. * * @param skillName - The skill name being requested * @returns SkillDescription if found and successfully fetched, undefined otherwise */ private getPromptSkillContent; /** * Builds the combined toolkit description using a single Liquid template. * * Collects all tools from connected MCP servers and all skills, then renders * them together using the toolkit-description.liquid template. * * Tool names are prefixed with serverName__ when the same tool exists * on multiple servers. Skill names are prefixed with skill__ when they * clash with MCP tools or other skills. * * @returns Object with rendered description and set of all tool names */ private buildToolkitDescription; /** * Gets the tool definition including available tools and skills in a unified format. * * The definition includes: * - All MCP tools from connected servers * - All available skills (file-based and prompt-based) * - Unified instructions for querying capability details * * Tool names are prefixed with serverName__ when clashing. * Skill names are prefixed with skill__ when clashing. * * @returns Tool definition with description and input schema */ getDefinition(): Promise; /** * Executes tool description lookup for the requested tool and skill names. * * Handles three types of lookups: * 1. skill__name - Returns skill information from SkillService * 2. serverName__toolName - Returns tool from specific server * 3. plainToolName - Returns tool(s) from all servers (multiple if clashing) * * @param input - Object containing toolNames array * @returns CallToolResult with tool/skill descriptions or error */ execute(input: DescribeToolsToolInput): Promise; } //#endregion //#region src/tools/SearchListToolsTool.d.ts interface SearchListToolsToolInput { capability?: string; serverName?: string; } declare class SearchListToolsTool implements Tool { private readonly _clientManager; private readonly definitionsCacheService; static readonly TOOL_NAME = "list_tools"; constructor(_clientManager: unknown, definitionsCacheService: DefinitionsCacheService); private formatToolName; getDefinition(): Promise; execute(input: SearchListToolsToolInput): Promise; } //#endregion //#region src/tools/UseToolTool.d.ts /** * Input schema for UseToolTool * @property toolName - Name of the tool or skill to execute * @property toolArgs - Arguments to pass to the tool (from describe_tools schema) */ interface UseToolToolInput { toolName: string; toolArgs?: Record; } /** * UseToolTool executes MCP tools and skills with proper error handling. * * This tool supports three invocation patterns: * 1. skill__skillName - Invokes a skill from the configured skills directory * 2. serverName__toolName - Invokes a tool on a specific MCP server * 3. plainToolName - Searches all servers for a unique tool match * * @example * const tool = new UseToolTool(clientManager, skillService); * await tool.execute({ toolName: 'skill__pdf' }); // Invoke a skill * await tool.execute({ toolName: 'playwright__browser_click', toolArgs: { ref: 'btn' } }); */ declare class UseToolTool implements Tool { static readonly TOOL_NAME = "use_tool"; private clientManager; private skillService; private definitionsCacheService; /** Unique server identifier for this one-mcp instance */ private serverId; /** * Creates a new UseToolTool instance * @param clientManager - The MCP client manager for accessing remote servers * @param skillService - Optional skill service for loading and executing skills * @param serverId - Unique server identifier for this one-mcp instance */ constructor(clientManager: McpClientManagerService, skillService?: SkillService, serverId?: string, definitionsCacheService?: DefinitionsCacheService); /** * Returns the MCP tool definition with name, description, and input schema. * * The definition describes how to use this tool to execute MCP tools or skills, * including the skill__ prefix format for skill invocations. * * @returns The tool definition conforming to MCP spec */ getDefinition(): ToolDefinition; /** * Returns guidance message for skill invocation. * * Skills are not executed via use_tool - they provide instructions that should * be followed directly. This method returns a message directing users to use * describe_tools to get the skill details and follow its instructions. * * @param skill - The skill that was requested * @returns CallToolResult with guidance message */ private executeSkill; /** * Finds a prompt-based skill by name from all connected MCP servers. * * @param skillName - The skill name to search for * @returns PromptSkillMatch if found, undefined otherwise */ private findPromptSkill; /** * Returns guidance message for prompt-based skill invocation. * * @param promptSkill - The prompt skill match that was found * @returns CallToolResult with guidance message */ private executePromptSkill; /** * Executes a tool or skill based on the provided input. * * Handles three invocation patterns: * 1. skill__skillName - Routes to skill execution via SkillService * 2. serverName__toolName - Routes to specific MCP server * 3. plainToolName - Searches all servers for unique match * * Edge cases: * - Returns error if skill not found when using skill__ prefix * - Returns error if tool is blacklisted on target server * - Returns disambiguation message if tool exists on multiple servers * * @param input - The tool/skill name and optional arguments * @returns CallToolResult with execution output or error */ execute(input: UseToolToolInput): Promise; } //#endregion //#region src/server/index.d.ts /** * Configuration options for creating an MCP server instance * @property configFilePath - Path to the MCP configuration file * @property noCache - Skip cache when fetching remote configuration * @property skills - Skills configuration with paths array (optional, skills disabled if not provided) * @property serverId - CLI-provided server ID (takes precedence over config file id) */ interface ServerOptions { configFilePath?: string; noCache?: boolean; skills?: { paths: string[]; }; serverId?: string; definitionsCachePath?: string; clearDefinitionsCache?: boolean; proxyMode?: 'meta' | 'flat' | 'search'; onServerIdResolved?: (serverId: string) => Promise | void; } /** * Shared services and tools for multi-session HTTP transport. * Created once via initializeSharedServices(), then passed to createSessionServer() * for each new client session. This avoids duplicating downstream connections, * file watchers, and caches across concurrent sessions. */ interface SharedServices { clientManager: McpClientManagerService; definitionsCacheService: DefinitionsCacheService; skillService?: SkillService; describeTools: DescribeToolsTool; useTool: UseToolTool; searchListTools: SearchListToolsTool; serverId: string; proxyMode: 'meta' | 'flat' | 'search'; /** * Disposes all shared resources: disconnects downstream servers, * stops file watchers. Must be called by the owner on shutdown. */ dispose: () => Promise; } /** * Initialize shared services and tools once for use across multiple sessions. * Use with createSessionServer() for HTTP transport where multiple agents * connect concurrently. This avoids duplicating downstream connections, * file watchers, caches, and tool instances per session. */ declare function initializeSharedServices(options?: ServerOptions): Promise; /** * Create a lightweight per-session MCP Server instance that delegates * to shared services and tools. Use with initializeSharedServices() * for multi-session HTTP transport. */ declare function createSessionServer(shared: SharedServices): Promise; /** * Create a single MCP server instance (backward-compatible wrapper). * For multi-session HTTP transport, use initializeSharedServices() + createSessionServer() instead. */ declare function createServer(options?: ServerOptions): Promise; //#endregion //#region src/transports/http.d.ts /** * HTTP transport handler using Streamable HTTP (protocol version 2025-03-26) * Provides stateful session management with resumability support */ declare class HttpTransportHandler implements HttpTransportHandler$1 { private serverFactory; private app; private server; private sessionManager; private config; private adminOptions?; private adminRateLimiter; constructor(serverFactory: (() => Server | Promise), config: TransportConfig, adminOptions?: HttpTransportAdminOptions); private setupMiddleware; private setupRoutes; private isAuthorizedShutdownRequest; private handleAdminShutdownRequest; private handlePostRequest; private handleGetRequest; private handleDeleteRequest; start(): Promise; stop(): Promise; getPort(): number; getHost(): string; } //#endregion //#region src/transports/sse.d.ts /** * SSE (Server-Sent Events) transport handler * Legacy transport for backwards compatibility (protocol version 2024-11-05) * Uses separate endpoints: /sse for SSE stream (GET) and /messages for client messages (POST) */ declare class SseTransportHandler implements HttpTransportHandler$1 { private serverFactory; private app; private server; private sessionManager; private config; constructor(serverFactory: Server | (() => Server), config: TransportConfig); private setupMiddleware; private setupRoutes; private handleSseConnection; private handlePostMessage; start(): Promise; stop(): Promise; getPort(): number; getHost(): string; } //#endregion //#region src/transports/stdio.d.ts /** * Stdio transport handler for MCP server * Used for command-line and direct integrations */ declare class StdioTransportHandler implements TransportHandler { private server; private transport; constructor(server: Server); start(): Promise; stop(): Promise; } //#endregion //#region src/transports/stdio-http.d.ts interface StdioHttpProxyTransportConfig { endpoint: URL; } /** * Transport that serves MCP over stdio and forwards MCP requests to an HTTP endpoint. */ declare class StdioHttpTransportHandler implements TransportHandler { private readonly endpoint; private stdioProxyServer; private stdioTransport; private httpClient; constructor(config: StdioHttpProxyTransportConfig); start(): Promise; stop(): Promise; private createProxyServer; } //#endregion //#region src/services/ConfigFetcherService.d.ts interface ConfigFetcherOptions { configFilePath?: string; cacheTtlMs?: number; useCache?: boolean; remoteCacheTtlMs?: number; } /** * Service for fetching and caching MCP server configurations from local file and remote sources * Supports merging multiple remote configs with local config */ declare class ConfigFetcherService { private configFilePath?; private cacheTtlMs; private cachedConfig; private lastFetchTime; private remoteConfigCache; constructor(options: ConfigFetcherOptions); /** * Fetch MCP configuration from local file and remote sources with caching * Merges remote configs with local config based on merge strategy * @param forceRefresh - Force reload from source, bypassing cache */ fetchConfiguration(forceRefresh?: boolean): Promise; /** * Load raw configuration data from a local file (supports JSON and YAML) * Returns unparsed config data to allow access to remoteConfigs */ private loadRawConfigFromFile; /** * Parse raw config data using Zod schema * Filters out remoteConfigs to avoid including them in the final config */ private parseConfig; /** * Load configuration from a remote URL with caching * * SECURITY NOTE: This method fetches remote configs based on URLs from the local config file. * This is intentional and safe because: * 1. URLs are user-controlled via their local config file (not external input) * 2. SSRF protection validates URLs before fetching (blocks private IPs, enforces HTTPS) * 3. Users explicitly opt-in to remote configs in their local configuration * 4. This enables centralized config management (intended feature, not a vulnerability) * * CodeQL alert "file-access-to-http" is a false positive here - we're not leaking * file contents to arbitrary URLs, we're fetching configs from user-specified sources. */ private loadFromUrl; /** * Interpolate environment variables in a string * Supports ${VAR_NAME} syntax */ private interpolateEnvVars; /** * Merge two MCP configurations based on the specified merge strategy * @param localConfig Configuration loaded from local file * @param remoteConfig Configuration loaded from remote URL * @param mergeStrategy Strategy for merging configs * @returns Merged configuration */ private mergeConfigurations; /** * Clear the cached configuration */ clearCache(): void; /** * Check if cache is valid */ isCacheValid(): boolean; } //#endregion //#region src/services/RuntimeStateService.d.ts /** * Runtime state persistence implementation. */ declare class RuntimeStateService implements RuntimeStateManager { private runtimeDir; constructor(runtimeDir?: string); /** * Resolve default runtime directory under the user's home cache path. * @returns Absolute runtime directory path */ static getDefaultRuntimeDir(): string; /** * Build runtime state file path for a given server ID. * @param serverId - Target one-mcp server identifier * @returns Absolute runtime file path */ private getRecordPath; /** * Persist a runtime state record. * @param record - Runtime metadata to persist * @returns Promise that resolves when write completes */ write(record: RuntimeStateRecord): Promise; /** * Read a runtime state record by server ID. * @param serverId - Target one-mcp server identifier * @returns Matching runtime record, or null when no record exists */ read(serverId: string): Promise; /** * List all persisted runtime records. * @returns Array of runtime records */ list(): Promise; /** * Remove a runtime state record by server ID. * @param serverId - Target one-mcp server identifier * @returns Promise that resolves when delete completes */ remove(serverId: string): Promise; } //#endregion //#region src/services/StopServerService/types.d.ts /** * Stop request options. * @property serverId - Explicit one-mcp server identifier to stop * @property host - Host fallback for runtime lookup * @property port - Port fallback for runtime lookup * @property force - Skip server ID verification against /health when true * @property timeoutMs - Maximum time to wait for shutdown completion */ interface StopServerRequest { serverId?: string; host?: string; port?: number; force?: boolean; timeoutMs?: number; } /** * Stop command result payload. * @property ok - Whether the shutdown completed successfully * @property serverId - Stopped one-mcp server identifier * @property host - Host that served the runtime * @property port - Port that served the runtime * @property message - Human-readable shutdown result message */ interface StopServerResult { ok: true; serverId: string; host: string; port: number; message: string; } //#endregion //#region src/services/StopServerService/StopServerService.d.ts /** * Service for resolving runtime targets and stopping them safely. */ declare class StopServerService { private runtimeStateService; constructor(runtimeStateService?: RuntimeStateManager); /** * Resolve a target runtime and stop it cooperatively. * @param request - Stop request options * @returns Stop result payload */ stop(request: StopServerRequest): Promise; /** * Resolve a runtime record from explicit ID or a unique host/port pair. * @param request - Stop request options * @returns Matching runtime record */ private resolveRuntime; /** * Read the runtime health payload. * @param runtime - Runtime to query * @param timeoutMs - Request timeout in milliseconds * @returns Reachability status and optional payload */ private fetchHealth; private requestLocalShutdown; /** * Poll until the target runtime is no longer reachable. * @param runtime - Runtime expected to stop * @param timeoutMs - Maximum wait time in milliseconds * @returns Promise that resolves when shutdown is observed */ private waitForShutdown; /** * Perform a fetch with an abort timeout. * @param url - Target URL * @param init - Fetch options * @param timeoutMs - Timeout in milliseconds * @returns Fetch response */ private fetchWithTimeout; } //#endregion //#region src/utils/findConfigFile.d.ts /** * Config File Finder Utility * * DESIGN PATTERNS: * - Utility function pattern for reusable logic * - Fail-fast pattern with early returns * - Environment variable configuration pattern * * CODING STANDARDS: * - Use sync filesystem operations for config discovery (performance) * - Check PROJECT_PATH environment variable first * - Fall back to current working directory * - Support both .yaml and .json extensions * - Return null if no config file is found * * AVOID: * - Throwing errors (return null instead for optional config) * - Hardcoded file names without extension variants * - Ignoring environment variables */ /** * Find MCP configuration file by checking PROJECT_PATH first, then cwd * Looks for both mcp-config.yaml and mcp-config.json * * @returns Absolute path to config file, or null if not found */ declare function findConfigFile(): string | null; //#endregion //#region src/utils/generateServerId.d.ts /** * generateServerId Utilities * * DESIGN PATTERNS: * - Pure functions with no side effects * - Single responsibility per function * - Functional programming approach * * CODING STANDARDS: * - Export individual functions, not classes * - Use descriptive function names with verbs * - Add JSDoc comments for complex logic * - Keep functions small and focused * * AVOID: * - Side effects (mutating external state) * - Stateful logic (use services for state) * - Complex external dependencies */ /** * Generate a short, human-readable server ID. * * Uses Node.js crypto.randomBytes for cryptographically secure randomness * with rejection sampling to avoid modulo bias. * * The generated ID: * - Is 6 characters long by default * - Uses only lowercase alphanumeric characters * - Excludes confusing characters (0, O, 1, l, I) * * @param length - Length of the ID to generate (default: 6) * @returns A random, human-readable ID * * @example * generateServerId() // "abc234" * generateServerId(4) // "x7mn" */ declare function generateServerId(length?: number): string; //#endregion export { CachedFileSkillInfo, CachedPromptSkillInfo, CachedServerDefinition, ConfigFetcherService, DefinitionsCacheFile, DefinitionsCacheService, DescribeToolsTool, HttpTransportAdminOptions, HttpTransportHandler, HttpTransportHealthResponse, HttpTransportShutdownResponse, McpClientConnection, McpClientManagerService, McpHttpConfig, McpPromptInfo, McpResourceInfo, McpServerConfig, McpServerTransportConfig, McpServerTransportType, McpSseConfig, McpStdioConfig, McpToolInfo, PromptConfig, PromptSkillConfig, RemoteMcpConfiguration, RuntimeLookupOptions, RuntimeStateManager, RuntimeStateRecord, RuntimeStateService, SearchListToolsTool, type ServerOptions, type SharedServices, Skill, SkillMetadata, SkillService, SkillsConfig, SseTransportHandler, StdioHttpTransportHandler, StdioTransportHandler, type StopServerRequest, type StopServerResult, StopServerService, TRANSPORT_MODE, Tool, ToolDefinition, TransportConfig, TransportHandler, TransportMode, UseToolTool, createServer, createSessionServer, findConfigFile, generateServerId, initializeSharedServices };