### Setup Function Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/changelog/0.1.x/0.1.14.md Example of a `setup()` function, likely used for initializing or configuring a module or skill. ```typescript function setup() { return { // ... }; } ``` -------------------------------- ### Clone and Install Basic Host Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/docs/mcp-specification/2025-11-25/extensions/apps-build.md Clone the ext-apps repository and install dependencies for the basic-host example to test your MCP App. ```bash git clone https://github.com/modelcontextprotocol/ext-apps.git cd ext-apps/examples/basic-host npm install ``` -------------------------------- ### Configure bunfig.toml for Project Installation Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/polish-docs-meta/SKILL.md Create or verify the `bunfig.toml` file at the project root for managing bun installation and run configurations. This example sets auto-install to fallback and frozen lockfile to false, and enables bun execution. ```toml [install] auto = "fallback" frozenLockfile = false [run] bun = true ``` -------------------------------- ### Node.js Server Entry Point with createApp Source: https://context7.com/cyanheads/mcp-ts-core/llms.txt Use `createApp` to compose core services, register tools/resources/prompts, and start the transport for a Node.js MCP server. The `setup` function is where domain-specific configuration is parsed and services are initialized. ```typescript import { createApp, tool, resource, prompt, z } from '@cyanheads/mcp-ts-core'; import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config'; // Server-specific config — parsed lazily in setup(), not at module load const ServerConfigSchema = z.object({ apiKey: z.string().describe('External API key'), maxResults: z.coerce.number().default(50), }); const greet = tool('greet', { description: 'Greet someone by name.', annotations: { readOnlyHint: true }, input: z.object({ name: z.string().describe('Name to greet') }), output: z.object({ message: z.string().describe('Greeting message') }), handler: async (input) => ({ message: `Hello, ${input.name}!` }), }); const handle = await createApp({ name: 'my-mcp-server', version: '1.0.0', tools: [greet], resources: [], prompts: [], extensions: { 'vendor/my-ext': { version: '1' } }, setup(core) { // Parse domain config and initialize services here const cfg = parseEnvConfig(ServerConfigSchema, { apiKey: 'MY_API_KEY', maxResults: 'MY_MAX_RESULTS', }); console.log('API key loaded, max results:', cfg.maxResults); // Store refs for use in handlers via module-level accessor pattern }, }); // handle.services → { config, logger, storage, rateLimiter, ... } // handle.shutdown() → graceful teardown ``` -------------------------------- ### Node.js createApp Entry Point Source: https://github.com/cyanheads/mcp-ts-core/blob/main/AGENTS.md Example of initializing the MCP TS Core application for a Node.js environment. It includes setting up tools, resources, prompts, extensions, and custom setup logic. ```typescript import { createApp } from '@cyanheads/mcp-ts-core'; import { allToolDefinitions } from './mcp-server/tools/index.js'; import { allResourceDefinitions } from './mcp-server/resources/index.js'; import { allPromptDefinitions } from './mcp-server/prompts/index.js'; await createApp({ name: 'my-mcp-server', version: '0.1.0', tools: allToolDefinitions, resources: allResourceDefinitions, prompts: allPromptDefinitions, extensions: { 'vendor/my-extension': { /* extension config */ }, }, setup(core) { initMyService(core.config, core.storage); }, }); ``` -------------------------------- ### Create Node.js Application Source: https://github.com/cyanheads/mcp-ts-core/blob/main/CLAUDE.md Example of creating a Node.js application using `createApp`. This includes defining tools, resources, prompts, extensions, and a setup function that runs after core services are initialized. ```typescript import { createApp } from '@cyanheads/mcp-ts-core'; import { allToolDefinitions } from './mcp-server/tools/index.js'; import { allResourceDefinitions } from './mcp-server/resources/index.js'; import { allPromptDefinitions } from './mcp-server/prompts/index.js'; await createApp({ name: 'my-mcp-server', // overrides package.json / MCP_SERVER_NAME version: '0.1.0', // overrides package.json / MCP_SERVER_VERSION tools: allToolDefinitions, resources: allResourceDefinitions, prompts: allPromptDefinitions, extensions: { // SEP-2133 extensions advertised in capabilities 'vendor/my-extension': { /* extension config */ }, }, setup(core) { // runs after core services init, before transport starts initMyService(core.config, core.storage); }, }); ``` -------------------------------- ### Vitest Configuration Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/changelog/0.1.x/0.1.14.md Configuration for Vitest, a Vite-native unit testing framework. This example shows basic setup. ```typescript import { defineConfig } from 'vitest/config'; export default defineConfig({ // ... }); ``` -------------------------------- ### Server Configuration Example using parseEnvConfig Source: https://github.com/cyanheads/mcp-ts-core/blob/main/changelog/0.5.x/0.5.0.md An example demonstrating how to use `parseEnvConfig` within `server-config.ts` to define and validate server configuration, including environment variables. ```typescript import { parseEnvConfig } from "@mcp/core/config"; import { z } from "zod"; const serverConfigSchema = z.object({ PORT: z.coerce.number().default(3000), NODE_ENV: z.enum(["development", "production"]).default("development"), API_KEY: z.string(), }); const envMap = { "API_KEY": "MY_API_KEY", }; export const serverConfig = parseEnvConfig(serverConfigSchema, envMap); // Example usage: console.log(`Server running on port ${serverConfig.PORT}`); ``` -------------------------------- ### Start Basic Host with Custom Server Source: https://github.com/cyanheads/mcp-ts-core/blob/main/docs/mcp-specification/2025-11-25/extensions/apps-build.md Start the basic-host test interface and configure it to connect to your local MCP server using the SERVERS environment variable. ```bash SERVERS='["http://localhost:3001/mcp"]' npm start ``` -------------------------------- ### Add Setup for Service Initialization Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/migrate-mcp-ts-template/SKILL.md If your server initializes services, include a `setup` function within the `createApp` call to handle this initialization. This function receives the core application context, allowing access to configuration and storage. ```typescript await createApp({ tools: [echoTool], resources: [echoResource], prompts: [echoPrompt], setup(core) { initMyService(core.config, core.storage); }, }); ``` -------------------------------- ### Package Arguments for `bun run start:stdio` Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/polish-docs-meta/references/server-json.md Defines the arguments passed to the package command when starting the server via stdio. ```json "packageArguments": [ { "type": "positional", "value": "run" }, { "type": "positional", "value": "start:stdio" } ] ``` -------------------------------- ### Context State Management Examples Source: https://github.com/cyanheads/mcp-ts-core/blob/main/CLAUDE.md Demonstrates how to use ctx.state for setting, getting, deleting, and listing tenant-scoped key-value data, including TTL and Zod validation. ```typescript await ctx.state.set('item:123', { name: 'Widget', count: 42 }); await ctx.state.set('item:123', data, { ttl: 3600 }); // with TTL (seconds) const item = await ctx.state.get('item:123'); // T | null const safe = await ctx.state.get('item:123', ItemSchema); // Zod-validated T | null await ctx.state.delete('item:123'); const values = await ctx.state.getMany(['item:1', 'item:2']); // Map const page = await ctx.state.list('item:', { cursor, limit: 20 }); // { items, cursor? } ``` -------------------------------- ### Starting MCP Server with Streamable HTTP Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/polish-docs-meta/references/readme.md Start the MCP server for Streamable HTTP connections. Ensure the necessary environment variables are set. ```sh MCP_TRANSPORT_TYPE=http MCP_HTTP_PORT=3010 ACME_API_KEY=... bun run start:http # Server listens at http://localhost:3010/mcp ``` -------------------------------- ### Tool Description: Prerequisite Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/design-mcp-server/SKILL.md Include operational guidance such as prerequisites in the tool description. This example specifies that setting the session working directory allows subsequent git commands to omit the path parameter. ```typescript description: 'Set the session working directory for all git operations. This allows subsequent git commands to omit the path parameter.' ``` -------------------------------- ### Start MCP Server Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/field-test/SKILL.md Starts the MCP server at the specified path. Ensure the server is built before starting. This function relies on `mcp-field-test.sh` and may require user confirmation if a process is already listening on the port. ```bash . /tmp/mcp-field-test.sh mcp_start /absolute/path/to/server # replace with the target server ``` -------------------------------- ### Example package.json Keywords Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/polish-docs-meta/references/package-meta.md This example shows how to structure the 'keywords' array in package.json to enhance npm discoverability. It includes base MCP keywords, domain-specific terms, and transport protocols. ```json "keywords": [ "mcp", "mcp-server", "model-context-protocol", "acme", "project-management", "task-tracking" ] ``` -------------------------------- ### Installing MCP Server Dependencies Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/polish-docs-meta/references/readme.md Install the project dependencies for the MCP server using Bun. ```sh bun install ``` -------------------------------- ### Example HTTP GET Request with Authorization Source: https://github.com/cyanheads/mcp-ts-core/blob/main/docs/mcp-specification/2025-06-18/core/authorization.md An example of an HTTP GET request to an MCP server, demonstrating the inclusion of the 'Authorization' header with a Bearer token. ```http GET /mcp HTTP/1.1 Host: mcp.example.com Authorization: Bearer eyJhbGciOiJIUzI1NiIs... ``` -------------------------------- ### Create Application with Tools, Resources, and Prompts Source: https://github.com/cyanheads/mcp-ts-core/blob/main/README.md Shows how to initialize the MCP application with a comprehensive configuration, including tools, resources, and prompts. This is the main entry point for setting up the server's capabilities. ```typescript await createApp({ name: 'my-mcp-server', version: '0.1.0', tools: allToolDefinitions, resources: allResourceDefinitions, prompts: allPromptDefinitions, }); ``` -------------------------------- ### RateLimiter Usage Examples Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/api-utils/references/security.md Demonstrates how to use the RateLimiter for checking requests, getting status, reconfiguring at runtime, and cleaning up on shutdown. ```typescript // In a service — check before expensive operation rateLimiter.check(`api:${ctx.tenantId}`, ctx); // Check status without consuming a request const status = rateLimiter.getStatus('api:tenant-123'); if (status) { logger.info(`${status.remaining} requests left, resets at ${new Date(status.resetTime)}`); } // Runtime reconfiguration rateLimiter.configure({ maxRequests: 200, windowMs: 60_000 }); // Cleanup on shutdown rateLimiter.dispose(); ``` -------------------------------- ### HTML Sanitization Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/api-utils/references/security.md Sanitize user-provided HTML content, allowing only specified tags and attributes. Ensure to install `sanitize-html` as a peer dependency. ```typescript const clean = await sanitization.sanitizeHtml(userHtml, { allowedTags: ['p', 'b', 'i', 'a'], allowedAttributes: { a: ['href'] }, }); ``` -------------------------------- ### Create a Basic MCP Server with a Tool Source: https://github.com/cyanheads/mcp-ts-core/blob/main/README.md Defines a simple 'greet' tool and initializes an MCP server application. This snippet demonstrates the core structure for creating a functional MCP server with custom tools. Ensure '@cyanheads/mcp-ts-core' is installed. ```typescript import { createApp, tool, z } from '@cyanheads/mcp-ts-core'; const greet = tool('greet', { description: 'Greet someone by name and return a personalized message.', annotations: { readOnlyHint: true }, input: z.object({ name: z.string().describe('Name of the person to greet'), }), output: z.object({ message: z.string().describe('The greeting message'), }), handler: async (input) => ({ message: `Hello, ${input.name}!`, }), }); await createApp({ tools: [greet] }); ``` -------------------------------- ### Initialize MCP Server Project Source: https://github.com/cyanheads/mcp-ts-core/blob/main/README.md Command to scaffold a new MCP server project using the framework's CLI. This sets up the basic project structure, including configuration files and directories for agent skills and tools. ```bash bunx @cyanheads/mcp-ts-core init my-mcp-server cd my-mcp-server bun install ``` -------------------------------- ### Configuring MCP Server Environment Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/polish-docs-meta/references/readme.md Copy the example environment file and edit it to set required variables for the MCP server. ```sh cp .env.example .env # edit .env and set required vars ``` -------------------------------- ### Cloudflare Workers createWorkerHandler Entry Point Source: https://github.com/cyanheads/mcp-ts-core/blob/main/AGENTS.md Example of setting up the MCP TS Core handler for Cloudflare Workers. This includes defining tools, resources, prompts, custom setup, environment bindings, and scheduled event handling. ```typescript import { createWorkerHandler } from '@cyanheads/mcp-ts-core/worker'; export default createWorkerHandler({ tools: allToolDefinitions, resources: allResourceDefinitions, prompts: allPromptDefinitions, setup(core) { initMyService(core.config, core.storage); }, extraEnvBindings: [['MY_API_KEY', 'MY_API_KEY']], extraObjectBindings: [['MY_CUSTOM_KV', 'MY_CUSTOM_KV']], onScheduled: async (controller, env, ctx) => { /* cron */ }, }); ``` -------------------------------- ### Run MCP App Source: https://github.com/cyanheads/mcp-ts-core/blob/main/docs/mcp-specification/2025-11-25/extensions/apps-build.md Install dependencies, build, and serve the generated MCP App. Ensure you are in the app's root directory before running these commands. ```bash npm install && npm run build && npm run serve ``` -------------------------------- ### createWorkerHandler Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/api-workers/SKILL.md The `createWorkerHandler` function is the entry point for Cloudflare Workers. It wraps registries into a per-request McpServer factory that integrates with the Cloudflare Workers runtime. The example shows how to import and configure it with tools, resources, prompts, a setup function, and extra environment and object bindings. ```APIDOC ## `createWorkerHandler(options)` ### Description Initializes a Cloudflare Worker handler with provided options. ### Options | Option | Type | Purpose | |:---|:---|:---| | `tools` | `AnyToolDefinition[]` | Tool definitions to register | | `resources` | `AnyResourceDefinition[]` | Resource definitions to register | | `prompts` | `PromptDefinition[]` | Prompt definitions to register | | `extensions` | `Record` | SEP-2133 extensions to advertise in server capabilities | | `setup` | `(core: CoreServices) => void | Promise` | Runs after core services are ready, during the first request (lazy init inside the fetch handler) | | `extraEnvBindings` | `[bindingKey: string, processEnvKey: string][]` | Maps CF string bindings to `process.env` keys | | `extraObjectBindings` | `[bindingKey: string, globalKey: string][]` | Maps CF object bindings (KV, R2, D1, AI) to `globalThis` keys | | `onScheduled` | `(controller, env, ctx) => Promise` | Cloudflare cron trigger handler | ### Example Usage ```ts import { createWorkerHandler } from '@cyanheads/mcp-ts-core/worker'; import { echoTool } from './mcp-server/tools/definitions/echo.tool.js'; import { echoResource } from './mcp-server/resources/definitions/echo.resource.js'; import { echoPrompt } from './mcp-server/prompts/definitions/echo.prompt.js'; import { initMyService } from './services/my-domain/my-service.js'; export default createWorkerHandler({ tools: [echoTool], resources: [echoResource], prompts: [echoPrompt], setup(core) { initMyService(core.config, core.storage); }, extraEnvBindings: [['MY_API_KEY', 'MY_API_KEY']], extraObjectBindings: [['MY_CUSTOM_KV', 'MY_CUSTOM_KV']], onScheduled: async (controller, env, ctx) => { // Cloudflare cron trigger handler }, }); ``` ``` -------------------------------- ### Health Check Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/api-services/references/speech.md Example of how to check the health status of the Speech Service. ```APIDOC ## Health Check ### Method Call the `healthCheck()` method on the `SpeechService` orchestrator. ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```ts const health = await speechService.healthCheck(); ``` ### Response #### Success Response - `health`: `object` - An object containing the health status of TTS and STT providers. - `tts`: `boolean` - Health status of the TTS provider. - `stt`: `boolean` - Health status of the STT provider. ``` -------------------------------- ### Install MCP SDK for Python Source: https://github.com/cyanheads/mcp-ts-core/blob/main/docs/mcp-specification/2025-11-25/extensions/auth-oauth-client-credentials.md Install the MCP SDK for Python using pip. ```bash pip install mcp ``` -------------------------------- ### Install MCP SDK for TypeScript Source: https://github.com/cyanheads/mcp-ts-core/blob/main/docs/mcp-specification/2025-11-25/extensions/auth-oauth-client-credentials.md Install the MCP SDK for TypeScript using npm. ```bash npm install @modelcontextprotocol/client ``` -------------------------------- ### Implement and Initialize a Service Source: https://github.com/cyanheads/mcp-ts-core/blob/main/AGENTS.md Create a service class with a constructor and methods. Initialize it once in setup and access it via a getter function. Services should not use `ctx.elicit` or `ctx.sample`. ```typescript export class MyService { constructor(private readonly config: AppConfig, private readonly storage: StorageService) {} async doWork(input: string, ctx: Context): Promise { ctx.log.debug('Working', { input }); return `done: ${input}`; } } let _service: MyService | undefined; export function initMyService(config: AppConfig, storage: StorageService): void { _service = new MyService(config, storage); } export function getMyService(): MyService { if (!_service) throw new Error('MyService not initialized — call initMyService() in setup()'); return _service; } ``` -------------------------------- ### Basic Error Throwing Examples Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/design-mcp-server/SKILL.md Illustrates different approaches to throwing errors. The first example shows a 'bad' dead-end error, while the subsequent examples demonstrate 'good' practices with recovery paths and structured hints. ```typescript // Bad — dead end, no recovery path throw new Error('Not found'); ``` ```typescript // Good — names both resolution options "No session working directory set. Please specify a 'path' or use 'git_set_working_dir' first." ``` -------------------------------- ### MCP Server README Structure Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/polish-docs-meta/references/readme.md This text block illustrates the recommended section order for an MCP server README file. Omit sections that do not apply to your specific server. ```text # {Server Name} ← centered HTML block [Public hosted callout if present] ← centered HTML block, directly under badges Badges row ← npm, Docker, Version, Framework, MCP SDK, License, TS, Bun, Coverage --- ## Tools ← grouping sentence → summary table → per-tool subsections ## Resources and prompts (if any) ← single combined table (Type / Name / Description) ## Features ← framework bullets + domain-specific bullets ## Getting started ← hosted (if any), bunx/npx/docker configs, HTTP one-liner, prerequisites, install ## Configuration ← env var table + `.env.example` pointer ## Running the server ← dev, production, Workers/Docker ## Project structure ← directory/purpose table ## Development guide ← link to CLAUDE.md, key rules ## Contributing ← brief ## License ← one line ``` -------------------------------- ### List Available Voices Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/api-services/references/speech.md Example of how to retrieve a list of available voices from a TTS provider. ```APIDOC ## List Available Voices ### Method Call the `getVoices()` method on an `ISpeechProvider` instance. ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```ts const ttsProvider = speechService.getTTSProvider(); const voices = await ttsProvider.getVoices(); ``` ### Response #### Success Response - `voices`: `Voice[]` - An array of available voice objects. ``` -------------------------------- ### Speech-to-Text Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/api-services/references/speech.md Example of how to use the SpeechService to transcribe audio to text using an STT provider. ```APIDOC ## Speech-to-Text Usage ### Method Access the STT provider via `speechService.getSTTProvider()` and then call the `speechToText` method. ### Endpoint N/A (SDK method) ### Parameters #### Request Body (for `speechToText` method) - **audio** (Buffer) - Required - The audio data. - **format** (string) - Required - The audio format (e.g., `'mp3'`). - **language** (string) - Required - The language of the audio (e.g., `'en'`). ### Request Example ```ts const sttProvider = speechService.getSTTProvider(); const sttResult = await sttProvider.speechToText({ audio: buffer, format: 'mp3', language: 'en', }); ``` ### Response #### Success Response - `sttResult`: `SpeechToTextResult` - The transcribed text. ``` -------------------------------- ### createApp() Source: https://github.com/cyanheads/mcp-ts-core/blob/main/CLAUDE.md Initializes and creates a new server application. Returns a ServerHandle which provides access to services and a shutdown method. ```APIDOC ## createApp() ### Description Creates a new server application instance. ### Returns - `Promise`: A promise that resolves to a ServerHandle object. ### ServerHandle Interface ```ts interface ServerHandle { shutdown(signal?: string): Promise; readonly services: CoreServices; } ``` ### CoreServices Interface ```ts interface CoreServices { config: AppConfig; logger: Logger; storage: StorageService; rateLimiter: RateLimiter; llmProvider?: ILlmProvider; speechService?: SpeechService; supabase?: SupabaseClient; } ``` ``` -------------------------------- ### sampling/createMessage - Follow-up Request with Tool Results Source: https://github.com/cyanheads/mcp-ts-core/blob/main/docs/mcp-specification/2025-11-25/client/sampling.md This example demonstrates a server-to-client request using the `sampling/createMessage` method. It includes a conversation history with user messages, assistant tool uses, and subsequent tool results, preparing for the next LLM turn. ```APIDOC ## sampling/createMessage ### Description Sends a new sampling request with tool results appended to the conversation history. ### Method `sampling/createMessage` ### Parameters #### Request Body - **jsonrpc** (string) - Required - Specifies the JSON-RPC version. - **id** (number) - Required - The request ID. - **method** (string) - Required - The method name, `sampling/createMessage`. - **params** (object) - Required - Parameters for the method. - **messages** (array) - Required - An array of message objects representing the conversation history. - **role** (string) - Required - The role of the message sender ('user' or 'assistant'). - **content** (object or array) - Required - The content of the message. Can be a single object or an array of objects. - **type** (string) - Required - The type of content ('text', 'tool_use', 'tool_result'). - **text** (string) - Required if type is 'text' - The text content. - **toolUseId** (string) - Required if type is 'tool_result' - The ID of the tool use being responded to. - **id** (string) - Required if type is 'tool_use' - The unique ID for the tool use. - **name** (string) - Required if type is 'tool_use' - The name of the tool. - **input** (object) - Required if type is 'tool_use' - The input arguments for the tool. - **tools** (array) - Optional - A list of available tools the LLM can use. - **name** (string) - Required - The name of the tool. - **description** (string) - Required - A description of the tool. - **inputSchema** (object) - Required - The JSON schema defining the tool's input. - **maxTokens** (number) - Optional - The maximum number of tokens to generate in the response. ### Request Example ```json { "jsonrpc": "2.0", "id": 2, "method": "sampling/createMessage", "params": { "messages": [ { "role": "user", "content": { "type": "text", "text": "What's the weather like in Paris and London?" } }, { "role": "assistant", "content": [ { "type": "tool_use", "id": "call_abc123", "name": "get_weather", "input": { "city": "Paris" } }, { "type": "tool_use", "id": "call_def456", "name": "get_weather", "input": { "city": "London" } } ] }, { "role": "user", "content": [ { "type": "tool_result", "toolUseId": "call_abc123", "content": [{ "type": "text", "text": "Weather in Paris: 18°C, partly cloudy" }] }, { "type": "tool_result", "toolUseId": "call_def456", "content": [{ "type": "text", "text": "Weather in London: 15°C, rainy" }] } ] } ], "tools": [ { "name": "get_weather", "description": "Get current weather for a city", "inputSchema": { "type": "object", "properties": { "city": { "type": "string" } }, "required": ["city"] } } ], "maxTokens": 1000 } } ``` ``` -------------------------------- ### Text-to-Speech Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/api-services/references/speech.md Example of how to use the SpeechService to synthesize speech from text using a TTS provider. ```APIDOC ## Text-to-Speech Usage ### Method Access the TTS provider via `speechService.getTTSProvider()` and then call the `textToSpeech` method. ### Endpoint N/A (SDK method) ### Parameters #### Request Body (for `textToSpeech` method) - **text** (string) - Required - The text to synthesize. - **voice** (object) - Required - Voice configuration. Should contain `voiceId` (string). - **format** (string) - Required - The audio format (e.g., `'mp3'`). ### Request Example ```ts const ttsProvider = speechService.getTTSProvider(); const ttsResult = await ttsProvider.textToSpeech({ text: 'Hello, world!', voice: { voiceId: 'some-voice-id' }, format: 'mp3', }); ``` ### Response #### Success Response - `ttsResult`: `TextToSpeechResult` - The synthesized audio data. ``` -------------------------------- ### Error Handling Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/docs/mcp-specification/2025-11-25/client/roots.md Example of a JSON-RPC error response when the client does not support the roots capability. ```APIDOC ## Error Handling ### Description Illustrates a standard JSON-RPC error response for unsupported methods or internal errors. ### Error Codes - `-32601`: Method not found (e.g., client does not support roots). - `-32603`: Internal errors. ### Error Response Example ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32601, "message": "Roots not supported", "data": { "reason": "Client does not have roots capability" } } } ``` ``` -------------------------------- ### Build and Serve MCP App Source: https://github.com/cyanheads/mcp-ts-core/blob/main/docs/mcp-specification/2025-11-25/extensions/apps-build.md Commands to build and serve your MCP App locally. Ensure you have Node.js and npm installed. ```bash npm run build && npm run serve ``` -------------------------------- ### Simple Text Request Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/docs/mcp-specification/2025-11-25/client/elicitation.md An example of an elicitation request for a simple text input. The response contains the accepted user input. ```json { "jsonrpc": "2.0", "id": 1, "method": "elicitation/create", "params": { "mode": "form", "message": "Please provide your GitHub username", "requestedSchema": { "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"] } } } ``` ```json { "jsonrpc": "2.0", "id": 1, "result": { "action": "accept", "content": { "name": "octocat" } } } ``` -------------------------------- ### Build and Run Local Development Server Source: https://github.com/cyanheads/mcp-ts-core/blob/main/skills/polish-docs-meta/references/readme.md Use these commands for one-time builds and to run the server locally using either stdio or HTTP transport. ```sh # One-time build bun run rebuild # Run the built server bun run start:stdio # or bun run start:http ``` -------------------------------- ### Implement a Service with Init/Accessor Pattern Source: https://github.com/cyanheads/mcp-ts-core/blob/main/CLAUDE.md Defines a service 'MyService' and provides functions to initialize and access it, ensuring it's only used after setup. ```typescript export class MyService { constructor(private readonly config: AppConfig, private readonly storage: StorageService) {} async doWork(input: string, ctx: Context): Promise { ctx.log.debug('Working', { input }); return `done: ${input}`; } } let _service: MyService | undefined; export function initMyService(config: AppConfig, storage: StorageService): void { _service = new MyService(config, storage); } export function getMyService(): MyService { if (!_service) throw new Error('MyService not initialized — call initMyService() in setup()'); return _service; } ``` -------------------------------- ### Changelog Frontmatter Example Source: https://github.com/cyanheads/mcp-ts-core/blob/main/templates/CLAUDE.md This is an example of the YAML frontmatter required for per-version changelog files. It includes a summary and optional flags for breaking or security changes. ```markdown --- summary: "One-line headline, ≤250 chars" # required — powers the rollup index breaking: false # optional — true flags breaking changes security: false # optional — true flags security fixes --- ``` -------------------------------- ### createApp Source: https://github.com/cyanheads/mcp-ts-core/blob/main/AGENTS.md Initializes and returns a new server application instance. This function returns a Promise that resolves to a ServerHandle object, which provides methods for managing the server lifecycle and accessing its services. ```APIDOC ## createApp() ### Description Creates and returns a new server application instance. ### Method `createApp()` ### Returns - `Promise`: A promise that resolves to a `ServerHandle` object, which contains methods for managing the server and accessing its services. ```