### Configure MCP Stdio Adapter for Local Tools (TypeScript) Source: https://github.com/atomicbi/mcphero/blob/master/README.md Provides an example of setting up the MCP Stdio adapter for local tool servers. It shows how to integrate it with the MCPHero builder and start the application. The documentation also outlines how action properties map to MCP tool properties and how MCP logging is handled. ```typescript import { mcphero, stdio } from 'mcphero' await mcphero({ name: 'my-tools', description: 'My Tools', version: '1.0.0' }) .with(stdio()) .mount(MyAction) .start() ``` -------------------------------- ### API Reference: mcphero(options) Source: https://github.com/atomicbi/mcphero/blob/master/README.md Documentation for the `mcphero` function, which creates a new MCPHero builder instance. It outlines the `MCPHeroOptions` interface, including `name`, `description`, and `version`, and the `MCPHero` interface with methods for adding adapters (`with`), mounting actions (`mount`), and starting the server (`start`). ```typescript function mcphero(options: MCPHeroOptions): MCPHero interface MCPHeroOptions { name: string // Server/app name description: string // Human-readable description version: string // Semantic version } interface MCPHero { with(generator: AdapterGenerator): MCPHero // Add an adapter mount(action: Action): MCPHero // Mount an action start(): Promise // Start all adapters } ``` -------------------------------- ### Running Multiple Adapters Simultaneously with MCPhere Source: https://github.com/atomicbi/mcphero/blob/master/README.md Demonstrates how to run an MCP server and a REST API concurrently using the same set of actions. It shows the initialization of MCPhere with stdio and Fastify adapters, mounting actions, and starting the server. All adapters start at the same time, with stdio communicating over stdin/stdout and Fastify listening on a specified port. ```typescript await mcphero({ name: 'my-platform', description: 'Multi-transport', version: '1.0.0' }) .with(stdio()) .with(fastify({ host: 'localhost', port: 8080, logger: true })) .mount(SearchAction) .mount(GreetAction) .mount(AnalyzeAction) .start() ``` -------------------------------- ### Initialize MCPHero Builder with Adapters and Actions Source: https://context7.com/atomicbi/mcphero/llms.txt Demonstrates how to create a new MCPHero builder instance, chain adapters (like stdio and fastify), mount actions, and start all adapters concurrently. It requires importing necessary functions from the 'mcphero' library. ```typescript import { mcphero, stdio, fastify } from 'mcphero' // Create a new MCPHero instance with server metadata const app = mcphero({ name: 'my-toolkit', // Server/app name description: 'A collection of useful tools', // Human-readable description version: '2.1.0' // Semantic version }) // Chain adapters and actions app .with(stdio()) // Add MCP stdio adapter .with(fastify({ host: 'localhost', port: 8080 })) // Add REST API adapter .mount(SearchAction) // Mount an action .mount(GreetAction) // Mount another action // Start all adapters concurrently await app.start() ``` -------------------------------- ### Serve an Action as an MCP Server Source: https://github.com/atomicbi/mcphero/blob/master/README.md Initialize an MCPHero server instance, attach the stdio adapter, mount the action, and start the server to make the tool available to MCP clients. ```typescript import { mcphero, stdio } from 'mcphero' import { GreetAction } from './actions/greet.js' await mcphero({ name: 'my-server', description: 'My MCP Server', version: '1.0.0' }) .with(stdio()) .mount(GreetAction) .start() ``` -------------------------------- ### Development Commands Source: https://github.com/atomicbi/mcphero/blob/master/README.md Common commands for developing the Mcphero project, including installing dependencies, building the project, and performing linting and type-checking. ```bash # Install dependencies pnpm install # Build pnpm build # Build in watch mode pnpm watch # Type-check pnpm typecheck # Lint pnpm lint # Lint + typecheck pnpm check ``` -------------------------------- ### Development Commands Source: https://github.com/atomicbi/mcphero/blob/master/README.md A collection of npm scripts for managing the development lifecycle of the MCPhero project, including installation, building, testing, and linting. ```APIDOC ## Development Commands ### Description Scripts to manage the development workflow for the MCPhero project. ### Commands - `pnpm install`: Installs project dependencies. - `pnpm build`: Builds the project. - `pnpm watch`: Builds the project in watch mode for continuous development. - `pnpm typecheck`: Performs type checking on the codebase. - `pnpm lint`: Lints the code to enforce style and quality standards. - `pnpm check`: Runs both linting and type checking. ### Requirements Requires Node.js version 18 or higher. ``` -------------------------------- ### Configuring CLI Arguments vs Options with Zod Source: https://github.com/atomicbi/mcphero/blob/master/README.md Explains how Zod fields are converted into CLI options by default and how to promote specific fields to positional arguments using the `args` property. This example defines a `DeployAction` with environment, tag, and dryRun fields, designating 'environment' and 'tag' as positional arguments. The example also shows the resulting CLI command and its output, noting that the `args` property only affects CLI adapters and not MCP or REST adapters. ```typescript export const DeployAction = createAction({ name: 'deploy', description: 'Deploy to an environment', input: z.object({ environment: z.string().describe('Target environment'), tag: z.string().describe('Release tag'), dryRun: z.boolean().describe('Simulate without deploying').default(false) }), args: ['environment', 'tag'], run: async ({ environment, tag, dryRun }, { logger }) => { logger.info(`Deploying ${tag} to ${environment}${dryRun ? ' (dry run)' : ''}`) // ... return { deployed: !dryRun } } }) ``` ```bash $ mytool deploy production v2.1.0 --dry-run ◇ mytool - deploy ℹ Deploying v2.1.0 to production (dry run) ``` -------------------------------- ### Define Transport-Agnostic Actions with Zod Schemas Source: https://context7.com/atomicbi/mcphero/llms.txt Shows how to define transport-agnostic actions using `createAction`. Actions include a name, description, Zod input schema, and an async `run` function. They receive a logger for logging and progress reporting. Examples include basic actions, actions with complex inputs and progress reporting, and actions configured for CLI positional arguments. ```typescript import z from 'zod' import { createAction } from 'mcphero' // Basic action with string and boolean inputs export const GreetAction = createAction({ name: 'greet', description: 'Greet someone by name', input: z.object({ name: z.string().describe('The name to greet'), enthusiastic: z.boolean().describe('Add excitement').default(false) }), run: async ({ name, enthusiastic }, { logger }) => { const greeting = enthusiastic ? `HELLO, ${name.toUpperCase()}!!!` : `Hello, ${name}.` logger.info(greeting) return { greeting } } }) // Action with complex nested objects and progress reporting export const TaskAction = createAction({ name: 'task', description: 'Execute a long-running task', input: z.object({ meta: z.object({ id: z.uuid(), name: z.string() }), stepCount: z.number().int().min(1).max(10).describe('Number of steps').default(5), stepDuration: z.number().int().min(1000).max(10000).describe('Time per step').default(1000) }), run: async ({ stepCount, stepDuration }, { logger }) => { logger.info(`Running ${stepCount} steps at ${stepDuration}ms each`) for (let i = 1; i <= stepCount; i++) { logger.progress({ progress: i, total: stepCount, message: `Executing step ${i}` }) await new Promise(resolve => setTimeout(resolve, stepDuration)) } return { completed: stepCount } } }) // Action with CLI positional arguments export const DeployAction = createAction({ name: 'deploy', description: 'Deploy to an environment', input: z.object({ environment: z.string().describe('Target environment'), tag: z.string().describe('Release tag'), dryRun: z.boolean().describe('Simulate without deploying').default(false) }), args: ['environment', 'tag'], // These become positional CLI arguments run: async ({ environment, tag, dryRun }, { logger }) => { logger.info(`Deploying ${tag} to ${environment}${dryRun ? ' (dry run)' : ''}`) return { deployed: !dryRun } } }) ``` -------------------------------- ### Handling Complex Input Types with Zod Schemas Source: https://github.com/atomicbi/mcphero/blob/master/README.md Illustrates the use of Zod's full expressiveness for defining complex input schemas in actions. This example defines an `ImportAction` with various field types including strings, numbers with constraints, optional records, and booleans. It details how these complex types are handled across different adapters: MCP uses JSON Schema, CLI accepts JSON strings for record types, and Fastify documents them as POST bodies. ```typescript export const ImportAction = createAction({ name: 'import', description: 'Import data from a source', input: z.object({ source: z.string().describe('Data source URL'), format: z.string().describe('File format').default('json'), batchSize: z.number().int().min(1).max(10000).describe('Records per batch').default(500), tags: z.record(z.string()).describe('Key-value metadata tags').optional(), overwrite: z.boolean().describe('Overwrite existing records').default(false) }), run: async (input, { logger }) => { logger.info(`Importing from ${input.source} in ${input.format} format`) logger.info(`Batch size: ${input.batchSize}, overwrite: ${input.overwrite}`) if (input.tags) { logger.debug(`Tags: ${JSON.stringify(input.tags)}`) } // ... return { imported: 1500 } } }) ``` -------------------------------- ### Build MCPHero Application with Adapters and Actions (TypeScript) Source: https://github.com/atomicbi/mcphero/blob/master/README.md Illustrates the fluent API of the MCPHero builder for configuring an application. It demonstrates adding adapters using `.with()` and mounting actions using `.mount()`. The `.start()` method initiates all configured adapters concurrently. ```typescript const app = mcphero({ name: 'my-toolkit', description: 'A collection of useful tools', version: '2.1.0' }) app .with(stdio()) // Add an adapter .with(http({ ... })) // Add another — they run in parallel .mount(SearchAction) // Mount an action .mount(GreetAction) // Mount another await app.start() // Start all adapters concurrently ``` -------------------------------- ### Initialize MCPHero Adapters (TypeScript) Source: https://github.com/atomicbi/mcphero/blob/master/README.md Shows how to initialize different MCPHero adapters, such as stdio, http, fastify, and cli. Each adapter can be configured with specific options like host and port. Multiple adapters can be used in parallel. ```typescript import { stdio, http, fastify, cli } from 'mcphero' // No config needed stdio() // Host and port required http({ host: '127.0.0.1', port: 3000 }) // Full Fastify options pass-through fastify({ host: 'localhost', port: 8080, logger: true }) // No config needed cli() ``` -------------------------------- ### CLI Adapter Source: https://github.com/atomicbi/mcphero/blob/master/README.md This adapter transforms your actions into a command-line application with help text, option parsing, and styled terminal output via clack. ```APIDOC ## CLI Adapter ### Description Transforms your actions into a complete command-line application with help text, option parsing, and styled terminal output via clack. ### Initialization Example ```typescript import { mcphero, cli } from 'mcphero' await mcphero({ name: 'mytool', description: 'My CLI Tool', version: '1.0.0' }) .with(cli()) .mount(GreetAction) .mount(SearchAction) .start() ``` ### Zod Type to CLI Option Mapping | Zod Type | CLI Representation | |----------|-------------------| | `z.string()` | `--option-name ` | | `z.number()` | `--option-name ` | | `z.boolean()` | `--option-name` / `--no-option-name` | | `z.record()` | `--option-name ` | | `.default(value)` | Sets the default in help text | | `.describe('...')` | Sets the option description | Field names are automatically converted to `kebab-case` for flags. Action names become `kebab-case` subcommands. ### Example Output ```bash $ mytool greet --name "World" --enthusiastic ◇ mytool - greet ℹ HELLO, WORLD!!! ``` ``` -------------------------------- ### Deploy Multiple Adapters Simultaneously Source: https://context7.com/atomicbi/mcphero/llms.txt Illustrates how to run multiple adapters (e.g., MCP stdio and Fastify REST API) concurrently from a single action definition, allowing the same logic to serve different transport protocols. ```typescript import { mcphero, stdio, http, fastify, cli, createAction } from 'mcphero' import z from 'zod' const SearchAction = createAction({ name: 'search', description: 'Search documents', input: z.object({ query: z.string().describe('Search query'), limit: z.number().int().default(10) }), run: async ({ query, limit }, { logger }) => { logger.info(`Searching: ${query}`) return { results: [], total: 0 } } }) await mcphero({ name: 'my-platform', description: 'Multi-transport Server', version: '1.0.0' }) .with(stdio()) .with(fastify({ host: 'localhost', port: 8080, logger: true })) .mount(SearchAction) .start() ``` -------------------------------- ### Create MCP stdio Server with TypeScript Source: https://context7.com/atomicbi/mcphero/llms.txt Sets up an MCP server using stdin/stdout for local tool execution. Actions are registered as tools, and logging is automatically handled. This adapter is suitable for integrating MCP tools directly into local development workflows. ```typescript import { mcphero, stdio, createAction } from 'mcphero' import z from 'zod' const SearchAction = createAction({ name: 'searchDocs', description: 'Search documents by query', input: z.object({ query: z.string().describe('Search query'), limit: z.number().int().min(1).max(100).default(10) }), run: async ({ query, limit }, { logger }) => { logger.info(`Searching for: ${query}`) // Your search logic here return { results: [], count: 0 } } }) // Start MCP stdio server await mcphero({ name: 'my-tools', description: 'My MCP Tools', version: '1.0.0' }) .with(stdio()) .mount(SearchAction) .start() // Configure in Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json): // { // "mcpServers": { // "my-tools": { // "command": "node", // "args": ["/absolute/path/to/server.js"] // } // } // } // Configure in Claude Code (.mcp.json in project root): // { // "mcpServers": { // "my-tools": { // "command": "pnpm", // "args": ["tsx", "server.ts"] // } // } // } ``` -------------------------------- ### Logging and Progress Source: https://github.com/atomicbi/mcphero/blob/master/README.md Details on how to use the logger and progress reporter available in the action context across different adapters. ```APIDOC ## Logging and Progress ### Description Every action receives a `context.logger` with eight severity levels plus a progress reporter. ### Usage Example ```typescript run: async (input, { logger }) => { logger.debug('Starting operation...') logger.info('Processing item') logger.warning('Rate limit approaching') logger.error('Failed to connect') // Progress reporting (renders as MCP progress notifications, // Fastify trace logs, or console output depending on adapter) for (let i = 1; i <= total; i++) { logger.progress({ progress: i, total: total, message: `Processing item ${i} of ${total}` }) await processItem(i) } return { processed: total } } ``` ### Logging Levels per Adapter | Level | MCP (stdio/http) | Fastify | CLI | |-------|-------------------|---------|-----| | `debug` | `notifications/message` | `logger.debug()` | `log.message()` | | `info` | `notifications/message` | `logger.info()` | `log.info()` | | `warning` | `notifications/message` | `logger.warn()` | `log.warn()` | | `error` | `notifications/message` | `logger.error()` | `log.error()` | | `critical` | `notifications/message` | `logger.fatal()` | `log.error()` | | `progress` | `notifications/progress` | `logger.trace()` | `console.info()` | ``` -------------------------------- ### MCP Stdio Adapter Source: https://context7.com/atomicbi/mcphero/llms.txt Creates an MCP server using stdin/stdout transport for local tool servers. Actions are registered as MCP tools with PascalCase names, and logging notifications are automatically wired. ```APIDOC ## stdio() - MCP Stdio Adapter ### Description Creates an MCP server using stdin/stdout transport for local tool servers. Actions are registered as MCP tools with PascalCase names, and logging notifications are automatically wired. ### Method `mcphero().with(stdio()).mount(action).start()` ### Endpoint N/A (stdin/stdout) ### Parameters None directly for `stdio()`, configuration is done via `mcphero()` options. ### Request Example ```typescript import { mcphero, stdio, createAction } from 'mcphero' import z from 'zod' const SearchAction = createAction({ name: 'searchDocs', description: 'Search documents by query', input: z.object({ query: z.string().describe('Search query'), limit: z.number().int().min(1).max(100).default(10) }), run: async ({ query, limit }, { logger }) => { logger.info(`Searching for: ${query}`) // Your search logic here return { results: [], count: 0 } } }) // Start MCP stdio server await mcphero({ name: 'my-tools', description: 'My MCP Tools', version: '1.0.0' }) .with(stdio()) .mount(SearchAction) .start() ``` ### Response N/A (stdin/stdout communication) ### Configuration Examples **Claude Desktop:** ```json { "mcpServers": { "my-tools": { "command": "node", "args": ["/absolute/path/to/server.js"] } } } ``` **Claude Code:** ```json { "mcpServers": { "my-tools": { "command": "pnpm", "args": ["tsx", "server.ts"] } } } ``` ``` -------------------------------- ### Create CLI Application with Zod Integration Source: https://context7.com/atomicbi/mcphero/llms.txt Demonstrates how to transform an action into a CLI application using the cli() adapter. It shows how Zod schemas are automatically mapped to CLI arguments and options. ```typescript import { mcphero, cli, createAction } from 'mcphero' import z from 'zod' const HelloAction = createAction({ name: 'hello', description: 'Say hello to someone', input: z.object({ name: z.string().describe('Name to greet'), type: z.enum(['cat', 'dog']).describe('Pet type') }), args: ['name'], run: async ({ name, type }, { logger }) => { const message = `Hello, ${name}, my ${type}` logger.info(message) return { message } } }) await mcphero({ name: 'mytool', description: 'My CLI Tool', version: '1.0.0' }) .with(cli()) .mount(HelloAction) .start() ``` -------------------------------- ### Build and Maintain MCPHero Projects Source: https://github.com/atomicbi/mcphero/blob/master/CLAUDE.md Standard build and maintenance commands for the MCPHero repository using pnpm. ```bash pnpm build pnpm watch pnpm typecheck pnpm lint pnpm check ``` -------------------------------- ### Run MCPHero Development Servers Source: https://github.com/atomicbi/mcphero/blob/master/CLAUDE.md Commands to execute live test servers for various adapters. These commands use tsx to run the TypeScript test files directly. ```bash pnpm tsx test/stdio.ts pnpm tsx test/http.ts pnpm tsx test/fastify.ts pnpm tsx test/cli.ts ``` -------------------------------- ### MCP Client Configuration for Claude Desktop Source: https://github.com/atomicbi/mcphero/blob/master/README.md Provides the JSON configuration snippet to add to the Claude Desktop configuration file (`~/Library/Application Support/Claude/claude_desktop_config.json`) for setting up MCP servers. It specifies the command and arguments to run the server, enabling integration with Claude Desktop. ```json { "mcpServers": { "my-tools": { "command": "node", "args": ["/absolute/path/to/server.js"] } } } ``` -------------------------------- ### Fastify REST API Adapter with Swagger Source: https://context7.com/atomicbi/mcphero/llms.txt Creates a REST API with auto-generated OpenAPI documentation and interactive Swagger UI via Scalar. Each action becomes a `POST /{action.name}` route with full JSON Schema validation. ```APIDOC ## fastify() - REST API Adapter with Swagger ### Description Creates a REST API with auto-generated OpenAPI documentation and interactive Swagger UI via Scalar. Each action becomes a `POST /{action.name}` route with full JSON Schema validation. ### Method `mcphero().with(fastify({...})).mount(action).start()` ### Endpoint - **POST `/{action.name}`**: Endpoint for invoking a specific action. - **GET `/`**: Serves the Scalar API Reference UI. ### Parameters - **host** (string) - Optional - The hostname or IP address to bind the server to. Defaults to `'localhost'`. - **port** (number) - Optional - The port number to listen on. Defaults to `8080`. - **logger** (boolean) - Optional - Enable Fastify logging. Defaults to `false`. ### Request Example ```typescript import { mcphero, fastify, createAction } from 'mcphero' import z from 'zod' const ImportAction = createAction({ name: 'import', description: 'Import data from a source', input: z.object({ source: z.string().describe('Data source URL'), format: z.string().describe('File format').default('json'), batchSize: z.number().int().min(1).max(10000).default(500), tags: z.record(z.string()).describe('Key-value metadata tags').optional() }), run: async (input, { logger }) => { logger.info(`Importing from ${input.source} in ${input.format} format`) return { imported: 1500, source: input.source } } }) // Start Fastify REST API server await mcphero({ name: 'my-api', description: 'My REST API', version: '1.0.0' }) .with(fastify({ host: 'localhost', port: 8080, logger: true // Enable Fastify logging })) .mount(ImportAction) .start() ``` ### Example Curl Request ```bash curl -X POST http://localhost:8080/import \ -H "Content-Type: application/json" \ -d '{"source": "https://api.example.com/data", "format": "csv", "batchSize": 1000}' ``` ### Response Example (Success 200) ```json { "imported": 1500, "source": "https://api.example.com/data" } ``` ### API Reference UI Access the interactive API documentation at `http://localhost:8080/` (or the configured host/port). ``` -------------------------------- ### Adapter Factories Source: https://github.com/atomicbi/mcphero/blob/master/README.md Provides factory functions to create different types of adapters for integrating MCPhero with various environments like stdin/stdout, HTTP, Fastify, and CLI. ```APIDOC ## Adapter Factories ### Description Factory functions for creating MCPhero adapters to integrate with different communication channels and environments. ### Factories - `stdio(): AdapterFactory` - Creates an adapter for MCP communication over standard input/output streams. - `http(options: HttpAdapterOptions): AdapterFactory` - Creates an HTTP adapter for MCP communication. Requires `HttpAdapterOptions`. - `fastify(options: FastifyAdapterOptions): AdapterFactory` - Creates a Fastify-based REST API adapter with Swagger support. Requires `FastifyAdapterOptions`. - `cli(): AdapterFactory` - Creates an adapter for CLI integration using commander and clack. ### Types #### `HttpAdapterOptions` - **host** (string) - Required - The host for the HTTP adapter. - **port** (number) - Required - The port for the HTTP adapter. - `...plus CreateMcpExpressAppOptions (e.g., allowedHosts)` #### `FastifyAdapterOptions` - **host** (string) - Optional - The host for the Fastify adapter. - **port** (number) - Optional - The port for the Fastify adapter. - `...plus all FastifyHttpOptions (logger, connectionTimeout, etc.)` ``` -------------------------------- ### Adapter Factory Implementations Source: https://github.com/atomicbi/mcphero/blob/master/README.md Provides factory functions to create different types of adapters for Mcphero. These include adapters for standard input/output, HTTP streams, Fastify REST APIs, and command-line interfaces. ```typescript // MCP over stdin/stdout function stdio(): AdapterFactory // MCP Streamable HTTP function http(options: HttpAdapterOptions): AdapterFactory interface HttpAdapterOptions { host: string port: number // ...plus CreateMcpExpressAppOptions (e.g., allowedHosts) } // Fastify REST API with Swagger function fastify(options: FastifyAdapterOptions): AdapterFactory interface FastifyAdapterOptions { host?: string port?: number // ...plus all FastifyHttpOptions (logger, connectionTimeout, etc.) } // CLI via commander + clack function cli(): AdapterFactory ``` -------------------------------- ### Claude Desktop / Claude Code MCP Server Configuration (JSON) Source: https://github.com/atomicbi/mcphero/blob/master/README.md A JSON configuration snippet for setting up MCP servers within Claude Desktop or Claude Code. It specifies the command to run and its arguments, allowing the MCPHero server to be launched and managed by the IDE. ```json { "mcpServers": { "my-tools": { "command": "node", "args": ["path/to/server.js"] } } } ``` -------------------------------- ### MCP Streamable HTTP Adapter Source: https://context7.com/atomicbi/mcphero/llms.txt Creates an MCP server over HTTP with Server-Sent Events (SSE) for streaming. Supports multiple concurrent sessions, resumability via `Last-Event-ID`, and session termination. ```APIDOC ## http() - MCP Streamable HTTP Adapter ### Description Creates an MCP server over HTTP with Server-Sent Events (SSE) for streaming. Supports multiple concurrent sessions, resumability via `Last-Event-ID`, and session termination. ### Method `mcphero().with(http({...})).mount(action).start()` ### Endpoint Base endpoint: `/mcp` (configurable via `http` options) ### Parameters - **host** (string) - Optional - The hostname or IP address to bind the server to. Defaults to `'127.0.0.1'`. - **port** (number) - Optional - The port number to listen on. Defaults to `3000`. - **allowedHosts** (string[]) - Optional - A list of allowed hostnames for requests. Defaults to `['127.0.0.1']`. ### Request Example ```typescript import { mcphero, http, createAction } from 'mcphero' import z from 'zod' const AnalyzeAction = createAction({ name: 'analyze', description: 'Analyze data with progress', input: z.object({ data: z.array(z.string()).describe('Data to analyze') }), run: async ({ data }, { logger }) => { for (let i = 0; i < data.length; i++) { logger.progress({ progress: i + 1, total: data.length, message: `Processing item ${i + 1}` }) await new Promise(resolve => setTimeout(resolve, 100)) } return { analyzed: data.length } } }) // Start MCP HTTP server await mcphero({ name: 'my-tools', description: 'My MCP HTTP Server', version: '1.0.0' }) .with(http({ host: '127.0.0.1', port: 3000, allowedHosts: ['127.0.0.1'] })) .mount(AnalyzeAction) .start() ``` ### Exposed Endpoints - **POST `/mcp`**: Initialize session or invoke tools. - **GET `/mcp`**: Establish SSE stream for a session. - **DELETE `/mcp`**: Terminate a session. ### Client Connection Point MCP clients to: `http://127.0.0.1:3000/mcp` ### Response Example (SSE Stream) ``` id: event: data: ``` ``` -------------------------------- ### Action Logging and Progress Reporting Source: https://github.com/atomicbi/mcphero/blob/master/README.md Provides a context logger within each action with eight severity levels and a progress reporter. The logging output adapts to the adapter being used (MCP, Fastify, or CLI), offering consistent feedback across different environments. ```typescript run: async (input, { logger }) => { logger.debug('Starting operation...') logger.info('Processing item') logger.warning('Rate limit approaching') logger.error('Failed to connect') // Progress reporting (renders as MCP progress notifications, // Fastify trace logs, or console output depending on adapter) for (let i = 1; i <= total; i++) { logger.progress({ progress: i, total: total, message: `Processing item ${i} of ${total}` }) await processItem(i) } return { processed: total } } ``` -------------------------------- ### Define MCPHero Action with Zod Schema (TypeScript) Source: https://github.com/atomicbi/mcphero/blob/master/README.md Demonstrates how to create a transport-agnostic action using `createAction` from MCPHero. It defines input validation with Zod, including type checking, descriptions, and default values. The `run` function contains the core logic and receives validated input and a logger context. ```typescript import z from 'zod' import { createAction } from 'mcphero' export const SearchAction = createAction({ name: 'search', description: 'Search documents by query', input: z.object({ query: z.string().describe('Search query'), limit: z.number().int().min(1).max(100).describe('Max results').default(10), includeArchived: z.boolean().describe('Include archived documents').default(false) }), run: async ({ query, limit, includeArchived }, { logger }) => { logger.info(`Searching for: ${query}`) // ... your logic here const results = await performSearch(query, { limit, includeArchived }) return { results, count: results.length } } }) ``` -------------------------------- ### Implement Logging and Progress Reporting Source: https://context7.com/atomicbi/mcphero/llms.txt Shows how to utilize the logger interface within an action. It covers the eight severity levels and the progress reporting mechanism which adapts to the underlying transport. ```typescript import { createAction } from 'mcphero' import z from 'zod' export const ProcessAction = createAction({ name: 'process', description: 'Process items with logging', input: z.object({ items: z.array(z.string()), verbose: z.boolean().default(false) }), run: async ({ items, verbose }, { logger }) => { logger.debug('Debug: Starting operation...') logger.info('Info: Processing items') logger.notice('Notice: Important information') logger.warning('Warning: Rate limit approaching') logger.error('Error: Failed to connect') logger.critical('Critical: System failure') logger.alert('Alert: Immediate attention needed') logger.emergency('Emergency: System is unusable') const total = items.length for (let i = 1; i <= total; i++) { logger.progress({ progress: i, total: total, message: `Processing item ${i} of ${total}` }) await processItem(items[i - 1]) } return { processed: total } } }) ``` -------------------------------- ### Create MCP REST API with Fastify and Swagger using TypeScript Source: https://context7.com/atomicbi/mcphero/llms.txt Generates a REST API using Fastify, complete with auto-generated OpenAPI documentation and an interactive Swagger UI via Scalar. Each defined action is exposed as a `POST /{action.name}` route, enforcing strict JSON Schema validation for inputs. This adapter simplifies API creation and documentation. ```typescript import { mcphero, fastify, createAction } from 'mcphero' import z from 'zod' const ImportAction = createAction({ name: 'import', description: 'Import data from a source', input: z.object({ source: z.string().describe('Data source URL'), format: z.string().describe('File format').default('json'), batchSize: z.number().int().min(1).max(10000).default(500), tags: z.record(z.string()).describe('Key-value metadata tags').optional() }), run: async (input, { logger }) => { logger.info(`Importing from ${input.source} in ${input.format} format`) return { imported: 1500, source: input.source } } }) // Start Fastify REST API server await mcphero({ name: 'my-api', description: 'My REST API', version: '1.0.0' }) .with(fastify({ host: 'localhost', port: 8080, logger: true // Enable Fastify logging })) .mount(ImportAction) .start() // Routes created: // POST /import - Import data endpoint // GET / - Scalar API Reference UI // // Example curl request: // curl -X POST http://localhost:8080/import \ // -H "Content-Type: application/json" \ // -d '{"source": "https://api.example.com/data", "format": "csv", "batchSize": 1000}' // // Response: // {"imported": 1500, "source": "https://api.example.com/data"} ``` -------------------------------- ### Fastify REST API Adapter Source: https://github.com/atomicbi/mcphero/blob/master/README.md This adapter transforms your actions into a REST API with auto-generated OpenAPI documentation and an interactive Swagger UI powered by Scalar. ```APIDOC ## Fastify REST API Adapter ### Description Turns your actions into a REST API with auto-generated OpenAPI documentation and an interactive Swagger UI powered by Scalar. ### Initialization Example ```typescript import { mcphero, fastify } from 'mcphero' await mcphero({ name: 'my-api', description: 'My REST API', version: '1.0.0' }) .with(fastify({ host: 'localhost', port: 8080, logger: true })) .mount(SearchAction) .mount(GreetAction) .start() ``` ### Route Mapping Each action becomes a `POST /{action.name}` route. The Zod schema is converted to JSON Schema for request body validation and OpenAPI documentation. | Action | Route | Body | |--------|-------|------| | `name: 'search'` | `POST /search` | `{ "query": "...", "limit": 10 }` | | `name: 'greet'` | `POST /greet` | `{ "name": "World" }` | Visit `http://localhost:8080/` for the interactive Scalar API reference with try-it-out functionality. ### FastifyAdapterOptions Extends Fastify's native `FastifyHttpOptions`, so any Fastify config is supported: ```typescript fastify({ host: 'localhost', port: 8080, logger: { level: 'debug', transport: { target: 'pino-pretty' } }, connectionTimeout: 30000 }) ``` ``` -------------------------------- ### CLI Application Generation Source: https://github.com/atomicbi/mcphero/blob/master/README.md Transforms actions into a command-line application with help text, option parsing, and styled terminal output using clack. Zod types are automatically mapped to CLI options and descriptions, and action names become subcommands. ```typescript import { mcphero, cli } from 'mcphero' await mcphero({ name: 'mytool', description: 'My CLI Tool', version: '1.0.0' }) .with(cli()) .mount(GreetAction) .mount(SearchAction) .start() ``` -------------------------------- ### Define an Action with MCPHero Source: https://github.com/atomicbi/mcphero/blob/master/README.md Create a reusable Action by defining a name, Zod schema for input validation, and an async run function. This logic remains transport-agnostic. ```typescript import z from 'zod' import { createAction } from 'mcphero' export const GreetAction = createAction({ name: 'greet', description: 'Greet someone by name', input: z.object({ name: z.string().describe('The name to greet'), enthusiastic: z.boolean().describe('Add excitement').default(false) }), run: async ({ name, enthusiastic }, { logger }) => { const greeting = enthusiastic ? `HELLO, ${name.toUpperCase()}!!!` : `Hello, ${name}.` logger.info(greeting) return { greeting } } }) ``` -------------------------------- ### Create MCP HTTP Server with SSE using TypeScript Source: https://context7.com/atomicbi/mcphero/llms.txt Establishes an MCP server over HTTP utilizing Server-Sent Events (SSE) for real-time data streaming. It supports multiple concurrent sessions, session resumption using `Last-Event-ID`, and session termination. This is ideal for applications requiring live updates or progress reporting. ```typescript import { mcphero, http, createAction } from 'mcphero' import z from 'zod' const AnalyzeAction = createAction({ name: 'analyze', description: 'Analyze data with progress', input: z.object({ data: z.array(z.string()).describe('Data to analyze') }), run: async ({ data }, { logger }) => { for (let i = 0; i < data.length; i++) { logger.progress({ progress: i + 1, total: data.length, message: `Processing item ${i + 1}` }) await new Promise(resolve => setTimeout(resolve, 100)) } return { analyzed: data.length } } }) // Start MCP HTTP server await mcphero({ name: 'my-tools', description: 'My MCP HTTP Server', version: '1.0.0' }) .with(http({ host: '127.0.0.1', port: 3000, allowedHosts: ['127.0.0.1'] })) .mount(AnalyzeAction) .start() // Endpoints exposed: // POST /mcp - Initialize session or invoke tools // GET /mcp - Establish SSE stream for a session // DELETE /mcp - Terminate a session // // Point MCP clients to: http://127.0.0.1:3000/mcp ``` -------------------------------- ### Fastify REST API with OpenAPI and Swagger UI Source: https://github.com/atomicbi/mcphero/blob/master/README.md Transforms actions into a REST API with auto-generated OpenAPI documentation and an interactive Swagger UI powered by Scalar. Each action is mapped to a POST route, and Zod schemas are converted for request validation and documentation. ```typescript import { mcphero, fastify } from 'mcphero' await mcphero({ name: 'my-api', description: 'My REST API', version: '1.0.0' }) .with(fastify({ host: 'localhost', port: 8080, logger: true })) .mount(SearchAction) .mount(GreetAction) .start() ``` -------------------------------- ### MCP Client Configuration for MCP Inspector Source: https://github.com/atomicbi/mcphero/blob/master/README.md Details the JSON configuration for debugging with the MCP Inspector. Similar to the Claude Code configuration, it specifies the server command and arguments in a `.mcp.json` file. This configuration is used in conjunction with the `npx @modelcontextprotocol/inspector` command to launch the inspector with the specified server. ```json { "mcpServers": { "my-tools": { "command": "pnpm", "args": ["tsx", "server.ts"] } } } ``` ```bash npx @modelcontextprotocol/inspector --config .mcp.json --server my-tools ``` -------------------------------- ### MCP Client Configuration for Claude Code Source: https://github.com/atomicbi/mcphero/blob/master/README.md Shows the JSON configuration to be placed in a `.mcp.json` file in the project's root directory for configuring MCP servers when using Claude Code. It defines the command and arguments for running the server, typically using `pnpm` and `tsx` for execution. ```json { "mcpServers": { "my-tools": { "command": "pnpm", "args": ["tsx", "server.ts"] } } } ``` -------------------------------- ### HTTP Transport Configuration for MCP Source: https://github.com/atomicbi/mcphero/blob/master/README.md Provides the endpoint URL for connecting to the streamable HTTP adapter for MCP. Clients should be pointed to the `/mcp` endpoint on the specified host and port to establish communication. ```text http://127.0.0.1:3000/mcp ``` -------------------------------- ### Logger Interface Source: https://github.com/atomicbi/mcphero/blob/master/README.md Defines the structure and methods for logging within the MCPhero system, supporting various log levels from emergency to debug. ```APIDOC ## Logger Interface ### Description Defines the methods available for logging messages at different severity levels. ### Interface `Logger` ### Methods - `debug(data: unknown): void` - Logs a debug message. - `info(data: unknown): void` - Logs an informational message. - `notice(data: unknown): void` - Logs a notice message. - `warning(data: unknown): void` - Logs a warning message. - `error(data: unknown): void` - Logs an error message. - `critical(data: unknown): void` - Logs a critical message. - `alert(data: unknown): void` - Logs an alert message. - `emergency(data: unknown): void` - Logs an emergency message. - `progress(options: ProgressOptions): void` - Logs progress updates. ### Types #### `ProgressOptions` - **progress** (number) - Required - The current progress value. - **total** (number) - Optional - The total value for progress calculation. - **message** (string) - Optional - A message describing the progress. ``` -------------------------------- ### API Reference: createAction(action) Source: https://github.com/atomicbi/mcphero/blob/master/README.md Details the `createAction` function, a type-safe factory for creating actions. It returns the action object with full type inference and defines the `Action` interface, including properties like `name`, `description`, `input` schema (using Zod), optional `args`, and the `run` function. The `ActionContext` interface, providing a `logger`, is also described. ```typescript function createAction( action: Action ): Action interface Action { name: string description: string input: z.ZodType & { shape: Record } args?: (keyof I)[] run: (input: I, context: ActionContext) => Promise } interface ActionContext { logger: Logger } ``` -------------------------------- ### Streamable HTTP Transport with Server-Sent Events Source: https://github.com/atomicbi/mcphero/blob/master/README.md Implements a session-based MCP transport over HTTP using Server-Sent Events (SSE) for streaming. It supports concurrent sessions, resumability via Last-Event-ID, and automatic session termination. CORS is configured by default, exposing MCP-specific headers. ```typescript import { mcphero, http } from 'mcphero' await mcphero({ name: 'my-tools', description: 'My Tools', version: '1.0.0' }) .with(http({ host: '127.0.0.1', port: 3000, allowedHosts: ['127.0.0.1'] })) .mount(MyAction) .start() ``` -------------------------------- ### Logger Interface Definition Source: https://github.com/atomicbi/mcphero/blob/master/README.md Defines the structure for a Logger object, specifying methods for different logging levels (debug, info, warning, error, etc.) and a progress reporting mechanism. ```typescript interface Logger { debug: (data: unknown) => void info: (data: unknown) => void notice: (data: unknown) => void warning: (data: unknown) => void error: (data: unknown) => void critical: (data: unknown) => void alert: (data: unknown) => void emergency: (data: unknown) => void progress: (options: ProgressOptions) => void } interface ProgressOptions { progress: number total?: number message?: string } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.