### Start Method Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/gateway-server.md Connect the MCP server to the stdio transport, making it ready to receive requests from AI clients. ```typescript const server = new GatewayServer(); await server.start(); // Server is now listening for incoming MCP messages on stdio ``` -------------------------------- ### Quick Start Installation and Usage Source: https://github.com/hamidra/yamcp/blob/main/README.md Commands to install YAMCP, import servers, create workspaces, and run a workspace with an AI app. ```bash # Install YAMCP npm install -g yamcp # or use npx yamcp # Import servers (choose one) yamcp server import [config] # import servers from config file (see src/example-servers.json for format) yamcp server add # or add manually # create workspaces (e.g. a yam for coding, design, data, ...) yamcp yam create # Run workspace in your AI app yamcp run ``` -------------------------------- ### start Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/mcp-gateway.md Start the gateway: register request handlers, initialize the router with provider configs, and start accepting stdio connections from clients. ```typescript async start(providersConfig: McpProvider[]): Promise ``` ```typescript const providers: McpProvider[] = [ { namespace: "coding", type: "stdio", providerParameters: { command: "node", args: ["dist/server.js"] } } ]; await gateway.start(providers); console.log("Gateway is now listening on stdio"); ``` -------------------------------- ### Locating Configuration Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md Example of importing and logging configuration paths. ```typescript import { PROVIDERS_CONFIG_PATH, WORKSPACES_CONFIG_PATH, LOG_DIR } from "yamcp"; console.log("YAMCP Directories:"); console.log(` Providers: ${PROVIDERS_CONFIG_PATH}`); console.log(` Workspaces: ${WORKSPACES_CONFIG_PATH}`); console.log(` Logs: ${LOG_DIR}`); ``` -------------------------------- ### Migrating Configuration Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/store-loader.md Example of migrating configuration from an external format. ```typescript import { loadProviderConfigFile, addMcpProviders } from "yamcp"; // Import from external format const imported = loadProviderConfigFile("./legacy-servers.json"); // Add all to yamcp store addMcpProviders(imported); ``` -------------------------------- ### Loading Configuration Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/store-loader.md Example of loading provider and workspace maps. ```typescript import { loadProvidersMap, loadWorkspaceMap } from "yamcp"; const providers = loadProvidersMap(); const workspaces = loadWorkspaceMap(); // Safely access; both return empty objects if files don't exist if (Object.keys(providers).length === 0) { console.log("No providers configured"); } else { console.log(`${Object.keys(providers).length} providers available`); } ``` -------------------------------- ### Get Workspace Providers Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Example of filtering all MCP providers to get those specific to a given workspace. ```typescript import { getWorkspaceProviders } from "yamcp"; const allProviders = getMcpProviders(); const workspace = getWorkspaces()["development"]; const workspaceProviders = getWorkspaceProviders( allProviders, workspace, logger ); ``` -------------------------------- ### Initialize and Start Gateway Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Initializes and starts the YAMCP gateway with a router, server, and logger. ```typescript const router = new GatewayRouter(logger); const server = new GatewayServer(); const gateway = new McpGateway(router, server, logger); await gateway.start(providersConfig); ``` -------------------------------- ### Start Method Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/gateway-router.md Starts the router by connecting to all configured providers. This is equivalent to calling connect(). ```typescript async start(providersConfig: McpProvider[]): Promise ``` -------------------------------- ### EXAMPLE_SERVERS_CONFIG_PATH Constant Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md Path to the bundled example servers configuration file (for reference). ```typescript export const EXAMPLE_SERVERS_CONFIG_PATH: string ``` -------------------------------- ### Accessing Logs Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md Example of accessing workspace-specific logs using the LOG_DIR. ```typescript import { LOG_DIR } from "yamcp"; import fs from "fs"; import path from "path"; const workspaceLogs = path.join(LOG_DIR, "my-workspace_abc123d4"); const errorLog = path.join(workspaceLogs, "error.log"); if (fs.existsSync(errorLog)) { const errors = fs.readFileSync(errorLog, "utf-8"); console.log(errors); } ``` -------------------------------- ### Constructor Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/gateway-server.md Initialize a new gateway server with default configuration. ```typescript import { GatewayServer } from "yamcp"; const server = new GatewayServer(); ``` -------------------------------- ### Creating a Gateway in Application Code Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/README.md Example of how to set up and start a YAMCP Gateway within your application code, including logging, configuration loading, and graceful shutdown handling. ```typescript import { McpGateway, GatewayRouter, GatewayServer, Logger } from "yamcp"; import { loadProvidersMap, loadWorkspaceMap } from "yamcp"; // Setup logging const logger = new Logger("my-gateway"); // Load configuration const allProviders = loadProvidersMap(); const workspaces = loadWorkspaceMap(); // Get providers for a workspace const workspaceProviders = workspaces["development"].map(ns => allProviders[ns]); // Create and start gateway const router = new GatewayRouter(logger); const server = new GatewayServer(); const gateway = new McpGateway(router, server, logger); await gateway.start(workspaceProviders); console.log("Gateway running. Connect AI apps to stdio."); // Graceful shutdown process.on("SIGINT", async () => { await gateway.stop(); await logger.flushLogsAndExit(0); }); ``` -------------------------------- ### Modifying and Saving Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/store-loader.md Example demonstrating how to modify and save provider configurations. ```typescript import { loadProvidersMap, saveProviders, addMcpProviders } from "yamcp"; // Load current state let current = loadProvidersMap(); // Modify current["new"] = { ... }; // Save back saveProviders(current); // Or use convenience function addMcpProviders([{ namespace: "new", ... }]); ``` -------------------------------- ### workspaces.json Schema and Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md Stores workspace definitions. ```json { "workspace_name": ["provider1", "provider2"] } ``` ```json { "development": ["coding", "debugging"], "research": ["research", "data"], "all": ["coding", "debugging", "research", "data"] } ``` -------------------------------- ### Creating Provider Configuration Programmatically Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md Example of adding new MCP providers using the addMcpProviders function. ```typescript import { addMcpProviders } from "yamcp"; const newProviders = [ { namespace: "myservice", type: "stdio", providerParameters: { command: "python", args: ["-m", "myservice.mcp"] } } ]; addMcpProviders(newProviders); // Saved to PROVIDERS_CONFIG_PATH ``` -------------------------------- ### YAMCP UI Installation and Execution Source: https://github.com/hamidra/yamcp/blob/main/README.md Instructions on how to run the YAMCP UI directly using npx or by installing it globally. ```bash # Run directly with npx (recommended) npx yamcp-ui # Or install globally npm install -g yamcp-ui yamcp-ui ``` -------------------------------- ### connectProviderClient Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/provider-client.md Example usage of connectProviderClient to establish an MCP client connection. ```typescript import { getProviderClientTransport, connectProviderClient } from "yamcp"; const provider: McpProvider = { namespace: "coding", type: "stdio", providerParameters: { command: "node", args: ["server.js"] } }; const transport = getProviderClientTransport(provider); const client = await connectProviderClient(transport); // Now can use the client to call tools, list prompts, etc. const tools = await client.listTools(); const capabilities = await client.getServerCapabilities(); await client.close(); ``` -------------------------------- ### Stop Method Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/gateway-router.md Example of how to stop the router and clear its providers. ```typescript await router.stop(); router.providers = undefined; ``` -------------------------------- ### providers.json Schema and Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md Stores provider definitions. ```json { "namespace": { "namespace": "string", "type": "stdio" | "sse", "providerParameters": { // Depends on type (stdio or sse) } } } ``` ```json { "coding": { "namespace": "coding", "type": "stdio", "providerParameters": { "command": "node", "args": ["dist/server.js"], "env": { "DEBUG": "true" } } }, "research": { "namespace": "research", "type": "sse", "providerParameters": { "url": "http://localhost:3001" } } } ``` -------------------------------- ### Stop Method Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/gateway-server.md Close the MCP server and stdio transport. After stopping, the server can be restarted by calling `start()` again. ```typescript await server.stop(); ``` -------------------------------- ### saveWorkspaceMap Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/store-loader.md Example demonstrating how to load, modify, and save the workspace map. ```typescript import { loadWorkspaceMap, saveWorkspaceMap } from "yamcp"; let workspaces = loadWorkspaceMap(); workspaces["newworkspace"] = ["coding", "web"]; saveWorkspaceMap(workspaces); // Updated workspaces.json written to disk ``` -------------------------------- ### Display Workspace Choice Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Example of using displayWorkspacesChoice to present a selection of workspaces to the user. ```typescript import { displayWorkspacesChoice } from "yamcp"; const workspaces = getWorkspaces(); const selected = await displayWorkspacesChoice(workspaces); ``` -------------------------------- ### Parse Provider Options Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Example of using parseProviderParameters to create provider configurations for stdio and SSE types. ```typescript import { parseProviderParameters } from "yamcp"; const provider = parseProviderParameters("coding", { command: "node dist/server.js", env: ["DEBUG=true"] }); const sseProvider = parseProviderParameters("research", { url: "http://localhost:3001" }); ``` -------------------------------- ### Error Handling Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/store-loader.md Example demonstrating error handling when loading provider maps. ```typescript import { loadProvidersMap } from "yamcp"; try { const providers = loadProvidersMap(); // Use providers } catch (error) { if (error instanceof Error) { if (error.message.includes("not accessible")) { console.error("Cannot read config file (permission denied or not found)"); } else if (error.message.includes("Failed to parse")) { console.error("Config file is corrupted (invalid JSON)"); } else { // Zod validation error console.error("Config file contains invalid data:"); console.error(error.message); } } process.exit(1); } ``` -------------------------------- ### Constructor Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/gateway-router.md Initialize a new router instance with an optional logger. ```typescript import { GatewayRouter } from "yamcp"; import { Logger } from "yamcp"; const logger = new Logger("my-router"); const router = new GatewayRouter(logger); ``` -------------------------------- ### getProviderClientTransport Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/provider-client.md Example usage of getProviderClientTransport for both stdio and SSE providers. ```typescript import { getProviderClientTransport } from "yamcp"; // Stdio transport const stdioProvider: McpProvider = { namespace: "coding", type: "stdio", providerParameters: { command: "node", args: ["server.js"], env: { DEBUG: "true" } } }; const stdioTransport = getProviderClientTransport(stdioProvider); // Returns StdioClientTransport configured to spawn "node server.js" // SSE transport const sseProvider: McpProvider = { namespace: "research", type: "sse", providerParameters: { url: "http://localhost:3001" } }; const sseTransport = getProviderClientTransport(sseProvider); // Returns SSEClientTransport connecting to http://localhost:3001 ``` -------------------------------- ### Runtime Commands Source: https://github.com/hamidra/yamcp/blob/main/README.md Commands to start the gateway with a workspace and view logs. ```bash yamcp run # Start the gateway with specified workspace yamcp log # View server communication logs ``` -------------------------------- ### Config File Not Accessible Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/errors.md Example of an error message when a config file exists but is not readable. ```typescript // File exists but permission denied // Attempting to load config throws: // Error: Config file not accessible at ~/.local/share/yamcp/providers.json: EACCES: permission denied ``` -------------------------------- ### Configuration Paths Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Defines the default configuration paths for providers, workspaces, and logs across different operating systems, along with examples for workspace-specific logs. ```typescript import { PROVIDERS_CONFIG_PATH, WORKSPACES_CONFIG_PATH, LOG_DIR } from "yamcp"; // Provider store ${PROVIDERS_CONFIG_PATH} // Linux: ~/.local/share/yamcp/providers.json // macOS: ~/Library/Application Support/yamcp/providers.json // Windows: %APPDATA%/yamcp/providers.json // Workspace store ${WORKSPACES_CONFIG_PATH} // Linux: ~/.local/share/yamcp/workspaces.json // macOS: ~/Library/Application Support/yamcp/workspaces.json // Windows: %APPDATA%/yamcp/workspaces.json // Log directory ${LOG_DIR} // Linux: ~/.cache/yamcp/ // macOS: ~/Library/Caches/yamcp/ // Windows: %LOCALAPPDATA%/yamcp/ // Workspace logs ${LOG_DIR}${workspaceName}_${randomId}/error.log ${LOG_DIR}${workspaceName}_${randomId}/combined.log ``` -------------------------------- ### Command Reference Table Source: https://github.com/hamidra/yamcp/blob/main/README.md A table summarizing YAMCP commands, their descriptions, and examples. ```bash | Command | Description | Example | | ------------------ | ----------------------- | ------------------------------------ | | `server add` | Add a new MCP server | `yamcp server add` | | `server list` | List configured servers | `yamcp server list` | | `server remove` | Remove a server | `yamcp server remove [name]` | | `server import` | Import server config | `yamcp server import [config]` | | `yam create` | Create workspace | `yamcp yam create` | | `yam list` | List workspaces | `yamcp yam list` | | `yam list --name` | Show workspace details | `yamcp yam list --name my-workspace` | | `yam edit` | Edit workspace | `yamcp yam edit` | | `yam scan ` | Scan workspace | `yamcp yam scan [workspace-name]` | | `yam delete` | Delete workspace | `yamcp yam delete [workspace-name]` | | `run` | Start gateway | `yamcp run ` | | `log` | View logs | `yamcp log` | ``` -------------------------------- ### scanProvider Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/provider-scanner.md Example usage of the scanProvider function to connect to a provider and retrieve its capabilities and version information. ```typescript import { scanProvider } from "yamcp"; const provider = { namespace: "coding", type: "stdio", providerParameters: { command: "node", args: ["server.js"] } }; const result = await scanProvider(provider); if (result.connection.success) { console.log("✓ Connected successfully"); } if (result.capabilities.success && result.capabilities.data?.tools?.list) { console.log("Available tools:"); result.capabilities.data.tools.list.forEach(tool => { console.log(` - ${tool.name}: ${tool.description}`); }); } if (!result.version.success && result.version.error) { console.log(`Version check failed: ${result.version.error}`); } ``` -------------------------------- ### ListPrompts Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/gateway-router.md Aggregate prompts from all connected providers, prefixing each prompt name with its provider's namespace. ```typescript const prompts = await router.listPrompts(); console.log(prompts); // [ // { name: "coding_review", description: "Code review assistant" }, // { name: "data_analysis", description: "Data analysis guide" } // ] ``` -------------------------------- ### Processing Tool Lists Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/namespace-utility.md Example of processing tool lists by adding namespaces. ```typescript import { addNamespace, isNamespacedName, parseNamespace } from "yamcp"; // When listing tools from a provider const tools = [ { name: "run", description: "Run code" }, { name: "deploy", description: "Deploy service" } ]; const namespacedTools = tools.map(tool => ({ ...tool, name: addNamespace("coding", tool.name) })); // [ // { name: "coding_run", ... }, // { name: "coding_deploy", ... } // ] ``` -------------------------------- ### ListTools Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/gateway-router.md Aggregate tools from all connected providers, prefixing each tool name with its provider's namespace. ```typescript const tools = await router.listTools(); console.log(tools); // [ // { name: "coding_run", description: "Run code" }, // { name: "data_query", description: "Query database" } // ] ``` -------------------------------- ### Connect Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/gateway-router.md Establish connections to all configured providers in parallel. Failed provider connections are logged and silently skipped. ```typescript const configs: McpProvider[] = [ { namespace: "coding", type: "stdio", providerParameters: { command: "node", args: ["server.js"] } }, { namespace: "data", type: "sse", providerParameters: { url: "http://localhost:3000" } } ]; await router.connect(configs); // At this point, router.providers contains clients for successful connections ``` -------------------------------- ### Logger Constructor Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/logger.md Initializes a logger for a specific namespace and shows the default log file locations. ```typescript import { Logger } from "yamcp"; const logger = new Logger("my-gateway"); // Creates logs at: // $XDG_DATA_HOME/yamcp/logs/my-gateway/error.log // $XDG_DATA_HOME/yamcp/logs/my-gateway/combined.log ``` -------------------------------- ### Invalid Config JSON Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/errors.md Example of an error message when a config file contains invalid JSON syntax. ```typescript // providers.json contains: { "coding": { bad json } } // Attempting to load throws: // Error: Failed to parse config file: ~/.local/share/yamcp/providers.json // Unexpected token } in JSON at position 25 ``` -------------------------------- ### Routing Tool Requests Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/namespace-utility.md Example of routing tool requests using namespace utilities. ```typescript async function routeToolCall(toolName: string, args: any) { if (!isNamespacedName(toolName)) { throw new Error("Tool name must be namespaced"); } const { namespace, name } = parseNamespace(toolName); const provider = providers.get(namespace); if (!provider) { throw new Error(`Provider ${namespace} not found`); } return await provider.callTool(name, args); } ``` -------------------------------- ### getWorkspaces Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/workspace-store.md Retrieve all configured workspaces as a map of workspace name to provider namespace array. ```typescript import { getWorkspaces } from "yamcp"; const workspaces = getWorkspaces(); // { // "development": ["coding", "debugging"], // "research": ["research", "data", "web"] // } Object.entries(workspaces).forEach(([name, providers]) => { console.log(`Workspace: ${name}`); console.log(` Providers: ${providers.join(", ")}`); }); ``` -------------------------------- ### Logger Info Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/logger.md Logs an info-level message with optional metadata. ```typescript logger.info("Server started", { port: 3000, address: "localhost" }); ``` -------------------------------- ### RoutePromptRequest Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/gateway-router.md Route a prompt request to the appropriate provider based on the namespace prefix in the prompt name. ```typescript const result = await router.routePromptRequest({ method: "prompts/get", params: { name: "coding_review", arguments: { language: "typescript" } } }); ``` -------------------------------- ### getLogNamespace Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/logger.md Generates a unique log namespace for a workspace and demonstrates its usage with the Logger constructor. ```typescript import { getLogNamespace } from "yamcp"; const namespace = getLogNamespace("development"); // Returns something like "development_a1b2c3d4" const logger = new Logger(namespace); ``` -------------------------------- ### getMcpProviders Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/provider-store.md Retrieves all configured providers as a map of namespace to provider configuration. ```typescript import { getMcpProviders } from "yamcp"; const providers = getMcpProviders(); // { // "coding": { namespace: "coding", type: "stdio", ... }, // "research": { namespace: "research", type: "sse", ... } // } Object.entries(providers).forEach(([name, config]) => { console.log(`Provider: ${name} (${config.type})`); }); ``` -------------------------------- ### addWorkspace Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/workspace-store.md Create a new workspace or update an existing one with the given list of provider namespaces. ```typescript import { addWorkspace } from "yamcp"; addWorkspace("development", ["coding", "debugging"]); // Workspace "development" is created with two providers addWorkspace("research", ["research", "data", "web"]); // Another workspace "research" is created with three providers ``` -------------------------------- ### Testing Provider Connectivity Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/README.md Example code demonstrating how to scan a provider, check connection success, retrieve server version, and list capabilities. ```typescript import { scanProvider, getScanFailures } from "yamcp"; const result = await scanProvider(provider); if (result.connection.success) { console.log("✓ Connected"); } else { console.log(`✗ Connection failed: ${result.connection.error}`); } if (result.version.success) { console.log(`✓ Server: ${result.version.data.name} v${result.version.data.version}`); } if (result.capabilities.success) { const tools = result.capabilities.data?.tools?.list || []; const prompts = result.capabilities.data?.prompts?.list || []; console.log(`✓ ${tools.length} tools, ${prompts.length} prompts`); } else { console.log(`✗ Cannot read capabilities`); } ``` -------------------------------- ### removeAllProviders Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/provider-store.md Deletes the entire providers configuration file, removing all providers at once. ```typescript import { removeAllProviders } from "yamcp"; removeAllProviders(); // All providers are deleted; providers.json is removed ``` -------------------------------- ### RouteToolRequest Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/gateway-router.md Route a tool call request to the appropriate provider based on the namespace prefix in the tool name. ```typescript const result = await router.routeToolRequest({ method: "tools/call", params: { name: "coding_run", arguments: { code: "console.log('hello')" } } }); ``` -------------------------------- ### Load and List Configuration Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Loads provider and workspace configurations and lists them with their types. ```typescript const providers = loadProvidersMap(); const workspaces = loadWorkspaceMap(); Object.entries(providers).forEach(([name, config]) => { console.log(`${name} (${config.type})`); }); ``` -------------------------------- ### Usage Pattern: Verify Provider Before Adding Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/provider-scanner.md Example of verifying a provider's health before adding it to the configuration. ```typescript const result = await scanProvider(newProvider); if (isScanSuccessful(result)) { console.log("✓ Provider is healthy, adding to config"); addMcpProviders([newProvider]); } else { const failures = getScanFailures(result); console.error("Provider scan failed:"); failures.forEach(f => console.error(` ${f}`)); // Can choose to add anyway or reject } ``` -------------------------------- ### addMcpProviders Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/provider-store.md Adds or updates multiple MCP providers in the configuration store. New providers with duplicate namespaces overwrite existing ones. ```typescript import { addMcpProviders } from "yamcp"; const newProviders = [ { namespace: "coding", type: "stdio", providerParameters: { command: "node", args: ["server.js"] } }, { namespace: "research", type: "sse", providerParameters: { url: "http://localhost:3001" } } ]; addMcpProviders(newProviders); // Providers are now persisted to providers.json ``` -------------------------------- ### Usage Pattern: Display Capabilities After Successful Scan Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/provider-scanner.md Example of displaying provider capabilities after a successful scan. ```typescript const result = await scanProvider(provider); if (result.capabilities.success && result.capabilities.data) { const caps = result.capabilities.data; if (caps.tools?.list) { console.log("Tools:"); caps.tools.list.forEach(t => console.log(` - ${t.name}`)); } if (caps.prompts?.list) { console.log("Prompts:"); caps.prompts.list.forEach(p => console.log(` - ${p.name}`)); } if (caps.resources?.list) { console.log("Resources:"); caps.resources.list.forEach(r => console.log(` - ${r.name}`)); } } ``` -------------------------------- ### Imports Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Core gateway classes, configuration, utilities, provider management, workspace management, loading, validation, provider testing, CLI utilities, and configuration constants. ```typescript // Core gateway classes import { McpGateway, GatewayRouter, GatewayServer } from "yamcp"; // Configuration and utilities import { Logger, getLogNamespace } from "yamcp"; import { addNamespace, isNamespacedName, parseNamespace } from "yamcp"; // Provider management import { addMcpProviders, removeMcpProvider, getMcpProviders } from "yamcp"; // Workspace management import { addWorkspace, removeWorkspace, getWorkspaces } from "yamcp"; // Loading and validation import { loadProvidersMap, loadWorkspaceMap, loadProviderConfigFile } from "yamcp"; // Provider testing import { scanProvider, isScanSuccessful, getScanFailures } from "yamcp"; // CLI utilities import { parseProviderParameters, scanProviderAndConfirm, getWorkspaceProviders } from "yamcp"; // Configuration constants import { VERSION, SERVER_NAME, PROVIDERS_CONFIG_PATH, WORKSPACES_CONFIG_PATH, LOG_DIR } from "yamcp"; ``` -------------------------------- ### Create Provider Configuration Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Defines configurations for Stdio and SSE providers, including namespace, type, and parameters. ```typescript // Stdio provider const provider = { namespace: "coding", type: "stdio", providerParameters: { command: "node", args: ["server.js"], env: { DEBUG: "true" } } }; // SSE provider const sseProvider = { namespace: "research", type: "sse", providerParameters: { url: "http://localhost:3001" } }; ``` -------------------------------- ### getScanFailures Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/provider-scanner.md Example usage of the getScanFailures function to extract error messages from a scan result. ```typescript import { scanProvider, getScanFailures } from "yamcp"; const result = await scanProvider(provider); const failures = getScanFailures(result); if (failures.length > 0) { console.log("Scan issues:"); failures.forEach(error => { console.log(` - ${error}`); }); } ``` -------------------------------- ### Aggregate Tools from All Providers Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Lists all available tools aggregated from all providers through the router. ```typescript const tools = await router.listTools(); // [ // { name: "coding_run", ... }, // { name: "research_query", ... } // ] ``` -------------------------------- ### isScanSuccessful Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/provider-scanner.md Example usage of the isScanSuccessful function to check if a provider scan was fully successful. ```typescript import { scanProvider, isScanSuccessful } from "yamcp"; const result = await scanProvider(provider); if (isScanSuccessful(result)) { console.log("Provider is fully operational"); } else { console.log("Provider has issues, but may still be usable"); } ``` -------------------------------- ### Create Workspace Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Adds a new workspace with a specified name and a list of associated provider namespaces. ```typescript addWorkspace("development", ["coding", "debugging"]); ``` -------------------------------- ### Logger Error Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/logger.md Logs an error with automatic stack trace extraction, including examples for error objects and strings. ```typescript try { // some operation } catch (err) { logger.error(err, { context: "provider connection" }); } // Also works with strings: logger.error("Connection failed"); ``` -------------------------------- ### Handle Config Errors Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Illustrates error handling for loading providers, including permission denied and parsing/validation errors. ```typescript try { const providers = loadProvidersMap(); } catch (error) { if (error instanceof Error) { if (error.message.includes("not accessible")) { // Permission denied } else if (error.message.includes("Failed to parse")) { // Invalid JSON } else { // Zod validation error } } } ``` -------------------------------- ### Constructor Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/mcp-gateway.md Initialize a new gateway instance with a router, server, and optional logger. ```typescript constructor(router: GatewayRouter, server: GatewayServer, logger?: Logger) ``` ```typescript import { McpGateway } from "yamcp"; import { GatewayRouter } from "yamcp"; import { GatewayServer } from "yamcp"; import { Logger } from "yamcp"; const router = new GatewayRouter(); const server = new GatewayServer(); const logger = new Logger("my-gateway"); const gateway = new McpGateway(router, server, logger); ``` -------------------------------- ### Version Info Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Displays the YAMCP version and gateway server name and version. ```typescript import { VERSION, SERVER_NAME, SERVER_VERSION } from "yamcp"; console.log(`YAMCP ${VERSION}`); console.log(`Gateway: ${SERVER_NAME} v${SERVER_VERSION}`); ``` -------------------------------- ### removeWorkspace Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/workspace-store.md Remove a workspace by name from the configuration store. ```typescript import { removeWorkspace } from "yamcp"; removeWorkspace("development"); // Workspace "development" is removed from workspaces.json ``` -------------------------------- ### Logger FlushLogs Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/logger.md Flushes all pending log writes and closes the logger. ```typescript await logger.flushLogs(); // Logs are now on disk, safe to exit ``` -------------------------------- ### Logger FlushLogsAndExit Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/logger.md Flushes logs and exits the process with a specified exit code. ```typescript process.on("SIGINT", async () => { await gateway.stop(); await logger.flushLogsAndExit(0); }); ``` -------------------------------- ### buildProviderOptions Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/cli-utilities.md Build simple selection options for provider prompts. ```typescript function buildProviderOptions(providers: McpProvider[], description: string): Array<{ title: string; value: McpProvider; description: string; }> ``` ```typescript const options = buildProviderOptions(providers, "Select a provider to remove"); // [ // { title: "- coding (stdio)", value: {...}, description: "..." }, // { title: "- research (sse)", value: {...}, description: "..." } // ] ``` -------------------------------- ### removeMcpProvider Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/provider-store.md Removes a single provider by namespace from the configuration store. ```typescript import { removeMcpProvider } from "yamcp"; removeMcpProvider("coding"); // Provider "coding" is removed from providers.json ``` -------------------------------- ### parseProviderParameters Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/cli-utilities.md Parse command-line options and construct a McpProvider configuration object. ```typescript function parseProviderParameters( name: string, options: { command?: string; env?: string[]; url?: string } ): McpProvider ``` ```typescript import { parseProviderParameters } from "yamcp"; // Stdio provider with command and args const provider1 = parseProviderParameters("coding", { command: 'node dist/server.js --port 3000', env: ["DEBUG=true", "API_KEY=secret"] }); // { // namespace: "coding", // type: "stdio", // providerParameters: { // command: "node", // args: ["dist/server.js", "--port", "3000"], // env: { DEBUG: "true", API_KEY: "secret" } // } // } // SSE provider const provider2 = parseProviderParameters("research", { url: "http://localhost:3001" }); // { // namespace: "research", // type: "sse", // providerParameters: { // url: "http://localhost:3001" // } // } ``` -------------------------------- ### workspaces.json structure Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Defines the JSON structure for workspace configurations, mapping workspace names to provider lists. ```json { "workspace_name": ["provider1", "provider2"] } ``` -------------------------------- ### buildDetailedProviderOptions Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/cli-utilities.md Build detailed selection options for provider prompts, including tree visualization in descriptions. ```typescript function buildDetailedProviderOptions(providers: McpProvider[]): Array<{ title: string; value: McpProvider; description: string; }> ``` ```typescript const options = buildDetailedProviderOptions(providers); // Each option includes: // { // title: "- coding (stdio)", // value: { ... provider object ... }, // description: "... tree representation of config ..." // } ``` -------------------------------- ### Config Loading with Fallbacks Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/errors.md Shows how to load provider configurations with fallback mechanisms and specific error handling for file access and parsing issues. ```typescript import { loadProvidersMap } from "yamcp"; try { const providers = loadProvidersMap(); // Returns empty object if file doesn't exist // Throws if file exists but is invalid } catch (error) { if (error instanceof Error && error.message.includes("not accessible")) { console.error("Cannot read providers config"); process.exit(1); } else if (error instanceof Error && error.message.includes("Failed to parse")) { console.error("Providers config file is corrupted"); process.exit(1); } throw error; } ``` -------------------------------- ### providers.json structure Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Defines the JSON structure for provider configurations. ```json { "namespace": { "namespace": "string", "type": "stdio|sse", "providerParameters": { "command": "string", "args": ["string"], "env": { "KEY": "VALUE" }, "cwd": "string" } } } ``` -------------------------------- ### Route Tool Request Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Routes a tool request through the router, specifying the tool name and arguments. ```typescript const result = await router.routeToolRequest({ method: "tools/call", params: { name: "coding_run", arguments: { code: "..." } } }); ``` -------------------------------- ### Mcp Server Management Commands Source: https://github.com/hamidra/yamcp/blob/main/README.md Commands for managing MCP server configurations. ```bash yamcp server add # Add a new MCP server (interactive) yamcp server list # List all configured servers and their status yamcp server remove # Remove a server configuration yamcp server import # Import server configurations from a JSON file ``` -------------------------------- ### Top-Level Commands Structure Source: https://github.com/hamidra/yamcp/blob/main/README.md The general structure for YAMCP top-level commands. ```bash yamcp [command] [subcommand] [flags] ``` -------------------------------- ### Yam Workspace Management Commands Source: https://github.com/hamidra/yamcp/blob/main/README.md Commands for creating, managing, and running workspaces. ```bash yamcp yam create # Create a new workspace (interactive) yamcp yam list # List all workspaces or show specific workspace details yamcp yam edit # Modify an existing workspace configuration yamcp yam scan # Scan workspaces yamcp yam delete # Delete a workspace ``` -------------------------------- ### Logger LogMessage Example Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/logger.md Logs a message using the MCP-compatible log message format with different severity levels. ```typescript logger.logMessage({ level: "info", data: "Gateway started", _meta: { service: "yamcp-gateway" } }); logger.logMessage({ level: "error", data: "Connection lost", _meta: { provider: "coding", error_code: "ECONNREFUSED" } }); ``` -------------------------------- ### Check Scan Result Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Demonstrates how to check the success of connection, version, and capabilities scans and log errors. ```typescript const result = await scanProvider(provider); if (!result.connection.success) { console.error("Connection:", result.connection.error); } if (!result.version.success) { console.error("Version:", result.version.error); } if (!result.capabilities.success) { console.error("Capabilities:", result.capabilities.error); } ``` -------------------------------- ### Add Provider to Store Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Adds one or multiple providers to the MCP provider store. ```typescript // Add single addMcpProviders([newProvider]); // Add multiple addMcpProviders([provider1, provider2]); ``` -------------------------------- ### buildProviderTree Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/cli-utilities.md Build a tree representation of a provider configuration for CLI display. ```typescript function buildProviderTree(provider: McpProvider): TreeNode ``` ```typescript import { buildProviderTree } from "yamcp"; const provider = { namespace: "coding", type: "stdio", providerParameters: { command: "node", args: ["server.js"], env: { DEBUG: "true" } } }; const tree = buildProviderTree(provider); // Returns a nested structure like: // { // "coding": { // "Type: stdio": {}, // "Command: node": {}, // "Args: server.js": {}, // "Environment Variables": { // "DEBUG=true": {} // } // } // } ``` -------------------------------- ### scanProviderAndConfirm Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/cli-utilities.md Scan a provider and prompt user to confirm adding it if the scan fails. ```typescript async function scanProviderAndConfirm( mcpProvider: McpProvider, initial?: boolean ): Promise ``` ```typescript const confirmed = await scanProviderAndConfirm(newProvider); if (confirmed) { addMcpProviders([newProvider]); console.log("Provider added"); } else { console.log("Provider not added"); } ``` -------------------------------- ### Add Namespace Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Adds a namespace prefix to a given name. ```typescript const namespaced = addNamespace("coding", "run"); // Returns: "coding_run" ``` -------------------------------- ### Error Handling - Routing Errors Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/README.md Example code demonstrating how to handle routing errors, specifically checking for invalid parameters like namespaced tool names or missing providers. ```typescript // Routing errors try { const result = await router.routeToolRequest({...}); } catch (e) { if (e.code === ErrorCode.InvalidParams) { // Tool name not namespaced or provider not found } } ``` -------------------------------- ### Error Handling - Validation Errors Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/README.md Example code demonstrating how to handle validation errors when loading providers, including permission issues, file not found, and JSON parsing errors. ```typescript // Validation errors try { const providers = loadProvidersMap(); } catch (e) { if (e.message.includes("not accessible")) { // Permission or file not found } else if (e.message.includes("Failed to parse")) { // Invalid JSON } else { // Schema validation error from Zod } } ``` -------------------------------- ### Update Workspace Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Updates an existing workspace by adding or changing its associated provider namespaces. ```typescript addWorkspace("development", ["coding", "web", "debugging"]); ``` -------------------------------- ### LOG_DIR Constant Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md Base directory for all YAMCP logs. Individual workspaces create subdirectories here. ```typescript export const LOG_DIR: string ``` ```typescript import { LOG_DIR } from "yamcp"; console.log(`Logs stored in: ${LOG_DIR}`); // Find logs for a workspace at: ${LOG_DIR}${workspaceName}/ ``` -------------------------------- ### displayWorkspacesChoice Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/cli-utilities.md Display an interactive prompt for the user to select a workspace. ```typescript async function displayWorkspacesChoice( workspaces: Record, promptMessage?: string ): Promise ``` ```typescript const workspaces = getWorkspaces(); const selected = await displayWorkspacesChoice(workspaces); if (selected) { console.log(`Selected workspace: ${selected}`); } else { console.log("No workspace selected"); } ``` -------------------------------- ### Handle Routing Errors Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Shows how to catch and handle McpError, specifically checking for ErrorCode.InvalidParams during tool routing. ```typescript import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types"; try { await router.routeToolRequest({...}); } catch (error) { if (error instanceof McpError) { if (error.code === ErrorCode.InvalidParams) { console.error("Invalid tool name or provider not found"); } } } ``` -------------------------------- ### SERVER_VERSION Constant Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md Version of the MCP server, matches the VERSION constant. ```typescript export const SERVER_VERSION: string ``` -------------------------------- ### buildWorkspaceTree Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/cli-utilities.md Build tree structure of workspaces and their providers for display. ```typescript function buildWorkspaceTree(workspaces: Record): Record> ``` -------------------------------- ### Log Messages Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Logs messages with different levels (info, error) and custom metadata, and flushes logs. ```typescript const logger = new Logger("my-namespace"); logger.info("Server started", { port: 3000 }); logger.error(error, { context: "connection" }); logger.logMessage({ level: "info", data: "Custom message", _meta: { service: "gateway" } }); await logger.flushLogs(); ``` -------------------------------- ### VERSION Constant Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md Current YAMCP version from package.json. ```typescript export const VERSION: string ``` ```typescript import { VERSION } from "yamcp"; console.log(`YAMCP ${VERSION}`); ``` -------------------------------- ### getWorkspaceProviders Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/cli-utilities.md Retrieve provider configurations for all namespaces in a workspace. Missing providers are logged and filtered out. ```typescript function getWorkspaceProviders( providers: Record, workspace: Namespace[], logger?: Logger ): McpProvider[] ``` ```typescript const allProviders = getMcpProviders(); // { coding: {...}, research: {...} } const workspace = ["coding", "missing"]; const workspaceProviders = getWorkspaceProviders(allProviders, workspace, logger); // Returns [{ namespace: "coding", ... }] // Logs error: "Provider missing not found" ``` -------------------------------- ### WORKSPACES_CONFIG_PATH Constant Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md Absolute path to the workspaces configuration file where workspace-to-provider mappings are persisted. ```typescript export const WORKSPACES_CONFIG_PATH: string ``` -------------------------------- ### Logging in Gateway Lifecycle Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/logger.md Shows how to use the Logger within the lifecycle of a gateway. ```typescript const logNamespace = getLogNamespace("development"); const logger = new Logger(logNamespace); try { logger.info("Starting gateway"); await gateway.start(providers); logger.info("Gateway started successfully"); process.on("SIGINT", async () => { logger.info("Shutting down"); await gateway.stop(); await logger.flushLogsAndExit(0); }); } catch (error) { logger.error(error); await logger.flushLogsAndExit(1); } ``` -------------------------------- ### PROVIDERS_CONFIG_PATH Constant Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md Absolute path to the providers configuration file where MCP provider definitions are persisted. ```typescript export const PROVIDERS_CONFIG_PATH: string ``` ```typescript import { PROVIDERS_CONFIG_PATH } from "yamcp"; console.log(`Providers stored at: ${PROVIDERS_CONFIG_PATH}`); ``` -------------------------------- ### Generate Unique Log Namespace Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Generates a unique log namespace with a random suffix for a given base name. ```typescript const logNamespace = getLogNamespace("development"); // Returns: "development_a1b2c3d4" (with random suffix) const logger = new Logger(logNamespace); ``` -------------------------------- ### Routing with Error Handling Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/errors.md Illustrates how to route a tool call and catch specific MCP errors, such as invalid parameters. ```typescript import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types"; async function routeToolCall(router, toolName, args) { try { return await router.routeToolRequest({ method: "tools/call", params: { name: toolName, arguments: args } }); } catch (error) { if (error instanceof McpError) { if (error.code === ErrorCode.InvalidParams) { console.error(`Invalid tool reference: ${toolName}`); } } throw error; } } ``` -------------------------------- ### SERVER_NAME Constant Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/configuration.md The name of the gateway MCP server exposed to AI clients. ```typescript export const SERVER_NAME = "yamcp_gateway" ``` -------------------------------- ### Test Provider Connectivity Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Scans a provider to check its operational status and retrieves failures if any. ```typescript const result = await scanProvider(provider); if (isScanSuccessful(result)) { console.log("Provider is operational"); } else { console.log("Failures:", getScanFailures(result)); } ``` -------------------------------- ### Type Guards Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/quick-reference.md Provides type guards for checking if a provider configuration is of type Stdio or SSE. ```typescript import { isStdioConfig, isSSEConfig } from "yamcp"; if (isStdioConfig(provider)) { console.log(provider.providerParameters.command); } if (isSSEConfig(provider)) { console.log(provider.providerParameters.url); } ``` -------------------------------- ### loadProviderConfigFile Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/store-loader.md Load provider configurations from a configuration file (typically used when importing from external sources). ```typescript import { loadProviderConfigFile } from "yamcp"; // Load from default location const providers = loadProviderConfigFile(); // Load from custom file const imported = loadProviderConfigFile("./my-servers.json"); providers.forEach(p => { console.log(`${p.namespace}: ${p.type}`); }); ``` -------------------------------- ### printScanResult Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/cli-utilities.md Print scan results in tree format, showing tools, prompts, and resources if available. ```typescript function printScanResult(scanResult: ScanResult): void ``` ```typescript const result = await scanProvider(provider); printScanResult(result); // Outputs: // Server Capabilities: // --------------------- // Tools // - run // - deploy // Prompts // - code_review ``` -------------------------------- ### Managing Workspaces Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/README.md Illustrates how to manage workspaces in YAMCP, including creating, updating, listing, and removing workspaces and their associated providers. ```typescript import { addWorkspace, getWorkspaces, removeWorkspace } from "yamcp"; // Create workspace addWorkspace("development", ["coding", "debugging", "web"]); // Update workspace addWorkspace("development", ["coding", "debugging"]); // List all const all = getWorkspaces(); console.log(all); // Delete removeWorkspace("development"); ``` -------------------------------- ### Basic Logging in Application Source: https://github.com/hamidra/yamcp/blob/main/_autodocs/api-reference/logger.md Demonstrates basic logging within an application using the Logger class. ```typescript const logger = new Logger("my-app"); logger.info("Application started"); try { const result = await doSomething(); logger.info("Operation succeeded", { result }); } catch (error) { logger.error(error, { operation: "doSomething" }); } await logger.flushLogs(); ```