### Starting the Muppet local development server Source: https://www.muppet.dev/docs/server/runtimes/basic Once dependencies are installed, this snippet shows how to start the local development server for your Muppet application. The `dev` script is a common command across different package managers, enabling local testing and development of your application. ```npm npm run dev ``` ```yarn yarn dev ``` ```pnpm pnpm dev ``` ```bun bun run dev ``` -------------------------------- ### Installing dependencies for a Muppet project Source: https://www.muppet.dev/docs/server/runtimes/basic After creating a new Muppet project, navigate into the project directory and use the respective package manager to install the required dependencies. This step prepares the project for development by downloading all necessary packages. ```npm cd my-app npm i ``` ```yarn cd my-app yarn ``` ```pnpm cd my-app pnpm i ``` ```bun cd my-app bun i ``` -------------------------------- ### Creating a new Muppet project with create-muppet Source: https://www.muppet.dev/docs/server/runtimes/basic This snippet demonstrates how to initialize a new Muppet application using the `create-muppet` command. It supports various package managers and runtimes like npm, yarn, pnpm, bun, and deno, creating a new directory `my-app` with the project template. ```npm npm create muppet@latest my-app ``` ```yarn yarn create muppet my-app ``` ```pnpm pnpm create muppet@latest my-app ``` ```bun bun create muppet@latest my-app ``` ```deno deno init --npm muppet@latest my-app ``` -------------------------------- ### Install @hono/mcp Package Source: https://www.muppet.dev/docs/hono-mcp Instructions for installing the @hono/mcp library using common JavaScript package managers. Choose the command corresponding to your preferred package manager. ```Shell npm install @hono/mcp ``` ```Shell pnpm add @hono/mcp ``` ```Shell yarn install @hono/mcp ``` ```Shell bun add @hono/mcp ``` -------------------------------- ### Starting Muppet MCP Inspector as a Standalone Package Source: https://www.muppet.dev/docs/inspector This command starts the Muppet MCP Inspector when it has been installed as a standalone package. It provides the same graphical interface for debugging MCP Servers, accessible via a web browser at `http://localhost:3553`. ```Shell npm @muppet-kit/inspector ``` ```Shell pnpm @muppet-kit/inspector ``` ```Shell yarn @muppet-kit/inspector ``` ```Shell bun @muppet-kit/inspector ``` -------------------------------- ### Initialize and Install Dependencies for Hono Project Source: https://www.muppet.dev/docs/server/quickstart/server This snippet demonstrates how to initialize a new Hono project using pnpm, specifically for a Node.js template. It then shows how to install necessary dependencies like 'muppet', '@modelcontextprotocol/sdk', '@hono/standard-validator', and 'zod' for validation, which are crucial for building the weather server. ```shell # Initialize a new hono project, here we are using nodejs but you can use any other template pnpm create hono@latest my-mcp -i -t nodejs -p pnpm # Install dependencies pnpm add muppet @modelcontextprotocol/sdk @hono/standard-validator # You can use any validation lib that supports Standard Schema pnpm add zod ``` -------------------------------- ### Starting the Muppet MCP Inspector via CLI Source: https://www.muppet.dev/docs/inspector This command initiates the Muppet MCP Inspector using the `muppet-kit` command-line tool. Once started, the Inspector provides a graphical interface accessible via a web browser at `http://localhost:3553` for debugging MCP Servers. ```Shell npm muppet-kit inspector ``` ```Shell pnpm muppet-kit inspector ``` ```Shell yarn muppet-kit inspector ``` ```Shell bun muppet-kit inspector ``` -------------------------------- ### Implementing SSE Hono Transport with Muppet and Hono Source: https://www.muppet.dev/docs/server/concepts/transports This example demonstrates how to set up an SSE Hono Transport layer using the `hono` framework and `muppet` library. It shows how to create a Hono application, define an SSE endpoint, handle incoming messages, and integrate with the `muppet` bridge for server-sent events. This setup is compatible with various runtimes like Node.js, Deno, Bun, and Cloudflare Workers. ```TypeScript import { serve } from "@hono/node-server"; import { Hono } from "hono"; import { bridge, muppet, type MuppetEnv } from "muppet"; import { SSEHonoTransport, streamSSE } from "muppet/streaming"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); // Define your tools, prompts, and resources here // ... const mcp = muppet(app, { name: "My Muppet", version: "1.0.0", }); let transport: SSEHonoTransport | null = null; const server = new Hono(); server.get("/sse", async (c) => { return streamSSE(c, async (stream) => { transport = new SSEHonoTransport("/messages"); transport.connectWithStream(stream); await bridge({ mcp, transport, }); }); }); server.post("/messages", async (c) => { if (!transport) { throw new Error("Transport not initialized"); } await transport.handlePostMessage(c); return c.text("ok"); }); server.onError((err, c) => { console.error(err); return c.body(err.message, 500); }); serve( { fetch: server.fetch, port: 3001, }, (info) => { console.log(`Server started at http://localhost:${info.port}`); }, ); ``` -------------------------------- ### Open Claude for Desktop Configuration File Source: https://www.muppet.dev/docs/server/quickstart/server This snippet shows how to open the `claude_desktop_config.json` file using VS Code on different operating systems. This file is essential for configuring Claude for Desktop's connection to custom MCP servers. Ensure VS Code is installed and accessible from your command line. ```Shell code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` ```PowerShell code $env:AppData\Claude\claude_desktop_config.json ``` -------------------------------- ### Example `muppet.config.js` Configuration Source: https://www.muppet.dev/docs/inspector/config This snippet demonstrates a basic `muppet.config.js` file. It imports `defineInspectorConfig` from `muppet-kit` and sets up two OpenAI models (`gpt-4.1-nano`, `gpt-4.1-mini`) along with Cloudflare tunneling. This file is placed in the project root and exports the configuration using `defineInspectorConfig`. ```javascript // muppet.config.js import { defineInspectorConfig } from "muppet-kit"; import { cloudflare } from "muppet-kit/tunnel"; import { openai } from "@ai-sdk/openai"; export default defineInspectorConfig({ models: [openai("gpt-4.1-nano"), openai("gpt-4.1-mini")], tunneling: cloudflare(), // ... rest of your configuration }); ``` -------------------------------- ### Configure MCP Server in Claude Desktop JSON Source: https://www.muppet.dev/docs/server/quickstart/server This JSON snippet demonstrates how to add a custom MCP server configuration to the `mcpServers` key within the `claude_desktop_config.json` file. It specifies the server name ('weather'), the command to launch it ('node'), and the absolute path to its entry point. Examples are provided for both MacOS/Linux and Windows environments, highlighting the path differences. ```JSON { "mcpServers": { "weather": { "command": "node", "args": [ "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js" ] } } } ``` ```JSON { "mcpServers": { "weather": { "command": "node", "args": [ "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js" ] } } } ``` -------------------------------- ### Setting up Muppet with Deno using SSE Transport Source: https://www.muppet.dev/docs/server/runtimes/deno This code snippet demonstrates how to initialize a Muppet server within a Deno environment using the Hono web framework and SSE (Server-Sent Events) for real-time communication. It defines an SSE endpoint for client connections and a POST endpoint to handle incoming messages, ensuring the transport layer is properly initialized. An error handler is also included for robust server operation. ```TypeScript let transport: SSEHonoTransport | null = null; const server = new Hono(); server.get("/sse", (c) => { return streamSSE(c, async (stream) => { transport = new SSEHonoTransport("/messages"); transport.connectWithStream(stream); await bridge({ mcp, transport, }); }); }); server.post("/messages", async (c) => { if (!transport) { throw new Error("Transport not initialized"); } await transport.handlePostMessage(c); return c.text("ok"); }); server.onError((err, c) => { console.error(err); return c.body(err.message, 500); }); Deno.serve(server.fetch); ``` -------------------------------- ### Bun SSE Transport Layer Setup with Hono Source: https://www.muppet.dev/docs/server/runtimes/bun This code demonstrates how to set up a server using Hono and Bun to handle Server-Sent Events (SSE) for Muppet. It initializes an SSEHonoTransport for SSE connections, bridges it with 'mcp' (Muppet Control Protocol), and handles incoming messages via a POST endpoint. The setup includes basic error handling. ```JavaScript let transport: SSEHonoTransport | null = null; const server = new Hono(); server.get("/sse", (c) => { return streamSSE(c, async (stream) => { transport = new SSEHonoTransport("/messages"); transport.connectWithStream(stream); await bridge({ mcp, transport, }); }); }); server.post("/messages", async (c) => { if (!transport) { throw new Error("Transport not initialized"); } await transport.handlePostMessage(c); return c.text("ok"); }); server.onError((err, c) => { console.error(err); return c.body(err.message, 500); }); export default server; ``` -------------------------------- ### Define Dynamic Muppet Resource with Completions in TypeScript Source: https://www.muppet.dev/docs/server/concepts/resources This example shows how to add a `completion` function to a dynamic resource. The `completion` function provides the LLM with a list of possible values for the URI variable, guiding the LLM in generating valid inputs for the resource. ```TypeScript import { Hono } from "hono"; import { type MuppetEnv, registerResources } from "muppet"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); app.post( "/documents", registerResources((c) => { return [ { type: "template", // This tells muppet that this is a dynamic resource uri: "https://lorem.{value}", name: "Todo list", mimeType: "text/plain", completion: ({ name, value }) => { return ["muppet", "hono", "mcps"]; }, }, ]; }), ); ``` -------------------------------- ### Serve MCP Server with Hono and @hono/mcp Source: https://www.muppet.dev/docs/hono-mcp Demonstrates how to set up a Hono application to serve a Model Context Protocol (MCP) server. It utilizes `@modelcontextprotocol/sdk/server/mcp.js` and `@hono/mcp`'s `StreamableHTTPTransport` to handle incoming requests at the `/mcp` endpoint, enabling streaming capabilities for environments like Cloudflare Workers or Deno. ```TypeScript import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' import { StreamableHTTPTransport } from '@hono/mcp' import { Hono } from 'hono' const app = new Hono() // Your MCP server implementation const mcpServer = new McpServer({ name: 'my-mcp-server', version: '1.0.0', }) app.all('/mcp', async (c) => { const transport = new StreamableHTTPTransport() await mcpServer.connect(transport) return transport.handleRequest(c) }) export default app ``` -------------------------------- ### Connecting Muppet to LLM with Bridge Function Source: https://www.muppet.dev/docs/server/concepts/muppet This example illustrates how to establish a connection, or 'bridge', between your Muppet server instance and a Large Language Model (LLM) using the `bridge` function. It integrates a `StdioServerTransport` for communication, ensuring the Muppet instance is fully initialized before bridging. ```typescript import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { Hono } from "hono"; import { muppet, bridge, type MuppetEnv } from "muppet"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); // Define your tools, prompts, and resources here // ... const instance = muppet(app, { name: "My Muppet", version: "1.0.0" }).then((mcp) => { if (!mcp) { throw new Error("MCP not initialized"); } bridge({ mcp, transport: new StdioServerTransport() }); }); ``` -------------------------------- ### Initialize Muppet Server with Stdio Transport Source: https://www.muppet.dev/docs/server/concepts/transports This code snippet demonstrates how to set up a Muppet server using `StdioServerTransport`. It imports necessary modules like `StdioServerTransport`, `Hono`, and `muppet`, then uses the `bridge` function to connect the Muppet instance to the standard I/O transport layer. This setup is ideal for local development or environments without network access. ```TypeScript import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { Hono } from "hono"; import { bridge, muppet, type MuppetEnv } from "muppet"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); // Define your tools, prompts, and resources here // ... bridge({ mcp: muppet(app, { name: "My Muppet", version: "1.0.0", }), transport: new StdioServerTransport(), }); ``` -------------------------------- ### Configuring Muppet MCP Inspector with muppet.config.js Source: https://www.muppet.dev/docs/inspector This JavaScript configuration file, `muppet.config.js`, is placed in your project's root directory to customize the MCP Inspector's behavior. It allows defining AI models to be used (e.g., OpenAI models) and setting up tunneling options, such as Cloudflare, for remote access. ```JavaScript import { defineInspectorConfig } from "muppet-kit"; import { cloudflare } from "muppet-kit/tunnel"; import { openai } from "@ai-sdk/openai"; export default defineInspectorConfig({ models: [openai("gpt-4.1-nano"), openai("gpt-4.1-mini")], tunneling: cloudflare(), // ... rest of your configuration }); ``` -------------------------------- ### Configure Custom Logger for Muppet Server Source: https://www.muppet.dev/docs/server/concepts/transports This example shows how to integrate a custom logger, specifically `pino`, with your Muppet server. By configuring the `logger` prop during server initialization, you can direct logs to a specified file (e.g., `muppet.log`), preventing interference with standard I/O streams like `console.log` when using transports that block them. ```TypeScript muppet(app, { logger: pino( pino.destination( "./muppet.log", ), ) }) ``` -------------------------------- ### Define a Custom Resource Fetcher for Muppet in TypeScript Source: https://www.muppet.dev/docs/server/concepts/resources This example demonstrates how to define a custom fetcher for resources within the Muppet instance configuration. The `resources` prop allows specifying a function (e.g., for the `https` protocol) that takes a URI and returns the corresponding resource data, potentially fetching it asynchronously from external sources. ```TypeScript import { Hono } from "hono"; import { muppet, type MuppetEnv } from "muppet"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); muppet(app, { name: "example-fetcher", version: "0.0.1", resources: { https: (uri) => { return [ { uri, text: "Todo list", mimeType: "text/plain", }, ]; }, }, }); ``` -------------------------------- ### Node.js `package.json` Build Script and Dependencies Source: https://www.muppet.dev/docs/server/quickstart/server This JSON configuration for a `package.json` file defines a `build` script that uses `esbuild` to bundle, minify, and compile a TypeScript source file for a Node.js platform. It also lists `esbuild` as a necessary dependency for the build process. ```json { "scripts": { "build": "esbuild --bundle --minify --platform=node --outfile=./build/index.js ./src/index.ts" }, "dependencies": { "esbuild": "^0.24.2" } } ``` -------------------------------- ### Creating a Muppet Instance with Hono.js Source: https://www.muppet.dev/docs/server/concepts/muppet This snippet demonstrates how to initialize a Muppet application instance using the `muppet` function within a Hono.js server. It sets up the basic structure for defining tools, prompts, and resources, and configures the instance with a name and version. ```typescript import { Hono } from "hono"; import { muppet, type MuppetEnv } from "muppet"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); // Define your tools, prompts, and resources here // ... const instance = muppet(app, { name: "My Muppet", version: "1.0.0" }); ``` -------------------------------- ### Importing Required Packages in TypeScript Source: https://www.muppet.dev/docs/server/quickstart/server This code block shows the necessary import statements for a TypeScript file (`src/index.ts`). It includes imports from `@modelcontextprotocol/sdk`, `hono`, `muppet`, and `zod`, which are essential for setting up the server, defining tools, and handling data validation. ```typescript import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { Hono } from 'hono'; import { type ToolResponseType, bridge, describeTool, mValidator, muppet, } from "muppet"; import z from "zod"; ``` -------------------------------- ### Setting up a Stateless MCP Server with Hono Source: https://www.muppet.dev/docs/hono-mcp/stateless This code demonstrates how to initialize a Stateless Model Context Protocol (MCP) server using `@modelcontextprotocol/sdk/server/mcp.js` and integrate it with a Hono application via `@hono/mcp`. It sets up a `StreamableHTTPTransport` to manage the connection and efficiently handle all incoming MCP requests on the `/mcp` endpoint, ensuring the server is connected before processing requests. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StreamableHTTPTransport } from "@hono/mcp"; import { Hono } from "hono"; const app = new Hono(); const mcpServer = new McpServer({ name: "my-mcp-server", version: "1.0.0", }); const transport = new StreamableHTTPTransport(); let isConnected = false; const connectedToServer = mcpServer.connect(transport).then(() => { isConnected = true; }); app.all("/mcp", async (c) => { if (!isConnected) await connectedToServer; return transport.handleRequest(c); }); export default app; ``` -------------------------------- ### Initialize and Bridge Muppet Server Application (TypeScript) Source: https://www.muppet.dev/docs/server/quickstart/server This code initializes a Muppet server application with a specified name and version. It then establishes a communication bridge between the Muppet Control Plane (MCP) and a StdioServerTransport, enabling the server to interact via standard input/output. ```typescript muppet(app, { name: "weather", version: "1.0.0", }).then((mcp) => { if (!mcp) { throw new Error("MCP not initialized"); } // Bridge the mcp with the transport bridge({ mcp, transport: new StdioServerTransport(), }); }); ``` -------------------------------- ### Defining a Simple Hello World Tool with Muppet and Hono Source: https://www.muppet.dev/docs/server/concepts/tools This TypeScript code demonstrates how to define a simple 'Hello World' tool using the Muppet framework with Hono. It sets up an API endpoint `/hello` that accepts a JSON payload with a `name` field, validates it using `zod` via `mValidator`, and returns a personalized greeting. The `describeTool` function registers the tool with a name and description for LLM consumption. `mValidator` supports various Standard Schema validation libraries like zod, valibot, arktype, and typebox. ```typescript import { Hono } from "hono"; import { type MuppetEnv, type ToolResponseType, describeTool, mValidator, } from "muppet"; import z from "zod"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); app.post( "/hello", describeTool({ name: "Hello World", description: "A simple hello world tool", }), mValidator( "json", z.object({ name: z.string(), }), ), (c) => { const { name } = c.req.valid("json"); return c.json([ { type: "text", text: `Hello ${name}!`, }, ]); }, ); ``` -------------------------------- ### Implementing 'get-alerts' Tool with Hono and Muppet Source: https://www.muppet.dev/docs/server/quickstart/server This snippet defines a POST endpoint `/get-alerts` using Hono, integrated with `muppet`'s `describeTool` for API documentation and `mValidator` for input validation using Zod. It handles requests to retrieve weather alerts for a given state, makes an API call to the National Weather Service, and formats the response for the client, including error handling for failed requests or no active alerts. ```typescript const app = new Hono(); // Define the get-alerts tool app.post( "/get-alerts", describeTool({ name: "get-alerts", description: "Get weather alerts for a state", }), mValidator( "json", z.object({ state: z .string() .length(2) .describe("Two-letter state code (e.g. CA, NY)"), }), ), async (c) => { const { state } = c.req.valid("json"); const stateCode = state.toUpperCase(); const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`; const alertsData = await makeNWSRequest(alertsUrl); if (!alertsData) { return c.json({ content: [ { type: "text", text: "Failed to retrieve alerts data", }, ], }); } const features = alertsData.features || []; if (features.length === 0) { return c.json({ content: [ { type: "text", text: `No active alerts for ${stateCode}`, }, ], }); } const formattedAlerts = features.map(formatAlert); const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`; return c.json({ content: [ { type: "text", text: alertsText, }, ], }); }, ); ``` -------------------------------- ### Implementing 'get-forecast' Tool with Hono and Muppet (Partial) Source: https://www.muppet.dev/docs/server/quickstart/server This snippet begins the definition of a POST endpoint `/get-forecast` using Hono, `describeTool`, and `mValidator`. It is designed to retrieve weather forecasts for a specific latitude and longitude, validating the input coordinates using Zod. The full implementation of the forecast logic is not included in this snippet. ```typescript app.post( "/get-forecast", describeTool({ name: "get-forecast", description: "Get weather forecast for a location", }), mValidator( "json", z.object({ latitude: z .number() .min(-90) .max(90) .describe("Latitude of the location"), longitude: z .number() .min(-180) .max(180) .describe("Longitude of the location"), }), ), ``` -------------------------------- ### Setting up Muppet with Hono and SSE Transport in Node.js Source: https://www.muppet.dev/docs/server/runtimes/nodejs This code snippet demonstrates how to initialize a Muppet server using the Hono web framework and an SSE (Server-Sent Events) transport layer in a Node.js environment. It defines an SSE endpoint for client connections and a POST endpoint to handle incoming messages, ensuring the transport is initialized before processing requests. The server also includes basic error handling and listens on port 3000. ```TypeScript let transport: SSEHonoTransport | null = null; const server = new Hono(); server.get("/sse", (c) => { return streamSSE(c, async (stream) => { transport = new SSEHonoTransport("/messages"); transport.connectWithStream(stream); await bridge({ mcp, transport, }); }); }); server.post("/messages", async (c) => { if (!transport) { throw new Error("Transport not initialized"); } await transport.handlePostMessage(c); return c.text("ok"); }); server.onError((err, c) => { console.error(err); return c.body(err.message, 500); }); serve({ fetch: server.fetch, port: 3000, }); ``` -------------------------------- ### Define a Dynamic Prompt Endpoint with Hono.js and Muppet Source: https://www.muppet.dev/docs/server/concepts/prompts This TypeScript code snippet demonstrates how to create an API endpoint using Hono.js that defines a reusable and dynamic prompt template with Muppet's `describePrompt` and `mValidator`. It sets up an endpoint `/explain-like-im-5` that takes a `topic` as input, validates it using Zod, and generates a user prompt. The `completion` property provides suggested values for the `topic` variable. ```TypeScript import { Hono } from "hono"; import { describePrompt, type MuppetEnv, mValidator, type PromptResponseType, } from "muppet"; import z from "zod"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); app.post( "/explain-like-im-5", describePrompt({ name: "Explain like I'm 5", description: "A prompt to explain an advance topic to a 5 year old", completion: ({ name, value }) => [ "quantum physics", "machine learning", "natural language processing", "artificial intelligence", ], }), mValidator( "json", z.object({ topic: z.string(), }), ), (c) => { const { topic } = c.req.valid("json"); return c.json([ { role: "user", content: { type: "text", text: `Explain ${topic} to me like I'm five`, }, }, ]); }, ); ``` -------------------------------- ### Integrating Hono OpenAPI Validators with Muppet for MCP Server Generation Source: https://www.muppet.dev/docs/server/openapi/hono-openapi This TypeScript code demonstrates how to set up a Hono application with a route defined using `hono-openapi`'s `describeRoute` and `zValidator`. It then shows how to initialize `muppet` by passing the Hono app and including `uniqueSymbol` in the `symbols` array, allowing `muppet` to scan and reuse the `hono-openapi` validators for generating an MCP server. ```TypeScript import { Hono } from "hono"; import { describeRoute, uniqueSymbol } from "hono-openapi"; import { validator as zValidator } from "hono-openapi/zod"; import { muppet, type MuppetEnv } from "muppet"; import z from "zod"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); app.get( "/products", describeRoute({ summary: "Get all products", description: "This endpoint returns a list of all products.", }), zValidator("query", z.object({ page: z.number().optional() })), async (c) => { return c.json([ { id: 1, name: "Product 1", price: 10.0, }, { id: 2, name: "Product 2", price: 20.0, }, ]); }, ); muppet(app, { name: "hono-openapi-mcp", version: "0.0.1", // By passing this, muppet will scan the hono-openapi middlewares too symbols: [uniqueSymbol], }); ``` -------------------------------- ### Generating an MCP Server from an OpenAPI Spec Source: https://www.muppet.dev/docs/server/openapi/openapi-specs This code snippet demonstrates how to initialize a Model Context Protocol (MCP) server using an existing OpenAPI specification. It imports the necessary `StdioServerTransport` for standard I/O communication and the `fromOpenAPI` function from Muppet. The `fromOpenAPI` function takes an OpenAPI spec object, which defines the API's structure, and automatically generates the corresponding MCP server routes as tools. The server is then bridged to the standard I/O transport. ```typescript import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { bridge } from "muppet"; import { fromOpenAPI } from "muppet/openapi"; const mcp = fromOpenAPI({ // Add your OpenAPI spec here info: { title: "My Muppet", version: "1.0.0", }, openapi: "3.1.0", paths: {}, }); bridge({ mcp, transport: new StdioServerTransport(), }); ``` -------------------------------- ### `muppet` Function Configuration Options Source: https://www.muppet.dev/docs/server/concepts/muppet This section details the configuration options available for the `muppet` function, which is used to initialize a Muppet application instance. These properties allow customization of event handling, resource fetching, logging, and application metadata. ```APIDOC muppet(app: Hono, config: object): Promise Configuration Options: | Prop | Type | Default | Description | |---|---|---|---| | `events?` | `Emitter` | - | An optional event emitter for client-to-server notifications. | | `resources?` | `Record` | - | An optional record of resource fetcher functions. | | `logger?` | `number` | - | An optional logger level. | | `version` | `string` | - | The version of the Muppet application. | | `name` | `string` | - | The name of the Muppet application. | ``` -------------------------------- ### Helper Functions and Interfaces for National Weather Service API Source: https://www.muppet.dev/docs/server/quickstart/server This section defines constants for the NWS API base URL and User-Agent. It includes a generic asynchronous helper function `makeNWSRequest` for fetching data from the NWS API with proper headers and error handling. Additionally, it defines TypeScript interfaces (`AlertFeature`, `ForecastPeriod`, `AlertsResponse`, `PointsResponse`, `ForecastResponse`) to structure the expected API responses and `formatAlert` for processing alert data into a readable string. ```typescript const NWS_API_BASE = "https://api.weather.gov"; const USER_AGENT = "weather-app/1.0"; // Helper function for making NWS API requests async function makeNWSRequest(url: string): Promise { const headers = { "User-Agent": USER_AGENT, Accept: "application/geo+json", }; try { const response = await fetch(url, { headers }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return (await response.json()) as T; } catch (error) { console.error("Error making NWS request:", error); return null; } } interface AlertFeature { properties: { event?: string; areaDesc?: string; severity?: string; status?: string; headline?: string; }; } // Format alert data function formatAlert(feature: AlertFeature): string { const props = feature.properties; return [ `Event: ${props.event || "Unknown"}`, `Area: ${props.areaDesc || "Unknown"}`, `Severity: ${props.severity || "Unknown"}`, `Status: ${props.status || "Unknown"}`, `Headline: ${props.headline || "No headline"}`, "---", ].join("\n"); } interface ForecastPeriod { name?: string; temperature?: number; temperatureUnit?: string; windSpeed?: string; windDirection?: string; shortForecast?: string; } interface AlertsResponse { features: AlertFeature[]; } interface PointsResponse { properties: { forecast?: string; }; } interface ForecastResponse { properties: { periods: ForecastPeriod[]; }; } ``` -------------------------------- ### Fetch and Format NWS Weather Forecast Data (TypeScript) Source: https://www.muppet.dev/docs/server/quickstart/server This asynchronous function retrieves weather forecast data from the NWS API based on provided latitude and longitude. It performs multiple API calls, handles potential errors for missing data or URLs, and formats the forecast periods into a readable text string for a ToolResponseType. ```typescript async (c) => { const { latitude, longitude } = c.req.valid("json"); // Get grid point data const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`; const pointsData = await makeNWSRequest(pointsUrl); if (!pointsData) { return c.json({ content: [ { type: "text", text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`, }, ], }); } const forecastUrl = pointsData.properties?.forecast; if (!forecastUrl) { return c.json({ content: [ { type: "text", text: "Failed to get forecast URL from grid point data", }, ], }); } // Get forecast data const forecastData = await makeNWSRequest(forecastUrl); if (!forecastData) { return c.json({ content: [ { type: "text", text: "Failed to retrieve forecast data", }, ], }); } const periods = forecastData.properties?.periods || []; if (periods.length === 0) { return c.json({ content: [ { type: "text", text: "No forecast periods available", }, ], }); } // Format forecast periods const formattedForecast = periods.map((period: ForecastPeriod) => [ `${period.name || "Unknown"}:`, `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`, `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`, `${period.shortForecast || "No forecast available"}`, "---", ].join("\n"), ); const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`; return c.json({ content: [ { type: "text", text: forecastText, }, ], }); }, ``` -------------------------------- ### Implementing Stateful MCP with Hono and @hono/mcp Source: https://www.muppet.dev/docs/hono-mcp/stateful This code demonstrates how to set up a stateful Model Context Protocol (MCP) server using Hono and `@hono/mcp`. It simulates a user context in a Hono middleware, then uses the user's ID as a session ID for the `StreamableHTTPTransport`. This ensures that all requests from a specific user are routed to the same MCP server instance, allowing for state maintenance and personalized interactions. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StreamableHTTPTransport } from "@hono/mcp"; import { Hono } from "hono"; type HonoEnv = { Variables: { user: { id: string; }; }; }; const app = new Hono().use(async (c, next) => { // Simulate user context c.set("user", { id: "random-user-id" }); await next(); }); function createMCPServer(id: string) { const mcpServer = new McpServer({ name: "my-mcp-server", version: "1.0.0", }); // Here you can add any stateful logic, such as storing user-specific data return mcpServer; } app.all("/mcp", async (c) => { const user = c.get("user"); const transport = new StreamableHTTPTransport({ sessionIdGenerator: () => user.id, }); const mcpServer = createMCPServer(); mcpServer.connect(transport); return transport.handleRequest(c); }); export default app; ``` -------------------------------- ### Register a Static Muppet Resource in TypeScript Source: https://www.muppet.dev/docs/server/concepts/resources This snippet illustrates how to define a static resource. Unlike dynamic resources, static resources have a fixed URI and do not include a `completion` function, making them consistently available at a predefined location. ```TypeScript import { Hono } from "hono"; import { type MuppetEnv, registerResources } from "muppet"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); app.post( "/documents", registerResources((c) => { return [ { uri: "https://lorem.ipsum", name: "Todo list", mimeType: "text/plain", }, ]; }), ); ``` -------------------------------- ### `defineInspectorConfig` Options Reference Source: https://www.muppet.dev/docs/inspector/config This section details the available configuration options for the `defineInspectorConfig` function used in `muppet.config.js`. It lists each property, its expected type, and its default value if applicable, allowing users to customize the Inspector's behavior. ```APIDOC defineInspectorConfig(options: object): InspectorConfig options: models?: (LanguageModelV1 | { model: LanguageModelV1; default?: boolean | undefined; })[] - Description: Array of language models to use with the Inspector. - Default: - tunneling?: TunnelHandler - Description: Configuration for tunneling, e.g., Cloudflare. - Default: - configurations?: TransportConfig | TransportConfig[] - Description: Transport configurations for the Inspector. - Default: - logger?: Logger - Description: Custom logger instance for the Inspector. - Default: - enableOpenAPI?: boolean - Description: Flag to enable or disable OpenAPI support. - Default: true enableTelemetry?: boolean - Description: Flag to enable or disable telemetry collection. - Default: true auto_open?: boolean - Description: Flag to automatically open the Inspector UI in the browser on startup. - Default: true host: string - Description: The host address the Inspector server will bind to. - Default: 0.0.0.0 port: number - Description: The port number the Inspector server will listen on. - Default: 3553 ``` -------------------------------- ### Define a Dynamic Muppet Resource in TypeScript Source: https://www.muppet.dev/docs/server/concepts/resources This snippet demonstrates how to register a dynamic resource using the `registerResources` function in a Hono application. Dynamic resources have URIs generated based on request parameters, indicated by `type: "template"`. This allows LLMs to customize resource access based on their input. ```TypeScript import { Hono } from "hono"; import { type MuppetEnv, registerResources } from "muppet"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); app.post( "/documents", registerResources((c) => { return [ { type: "template", // This tells muppet that this is a dynamic resource uri: "https://lorem.{ending}", name: "Todo list", mimeType: "text/plain", }, ]; }), ); ``` -------------------------------- ### `bridge` Function Parameters Source: https://www.muppet.dev/docs/server/concepts/muppet This section outlines the parameters for the `bridge` function, which connects a Muppet instance to an LLM via a specified transport layer. It requires a fully initialized Muppet instance and a compatible transport mechanism. ```APIDOC bridge(options: object): void Options: mcp: MuppetInstance Description: The initialized Muppet instance to connect. transport: ServerTransport Description: The transport layer to use for connecting to the LLM (e.g., StdioServerTransport). ``` -------------------------------- ### Setting up SSE and Durable Objects for LLM Transport in Cloudflare Workers Source: https://www.muppet.dev/docs/server/runtimes/cloudflare-workers This code demonstrates how to set up a Hono server within a Cloudflare Worker to handle Server-Sent Events (SSE) and manage a transport instance for LLM connections using Cloudflare Durable Objects. It shows how to persist the `SSEHonoTransport` across requests by storing it within a `MyDurableObject` instance, ensuring session continuity. The main `fetch` handler dispatches requests to the appropriate Durable Object based on a `sessionId` query parameter, creating a new instance if no session ID is provided. ```TypeScript const server = new Hono<{ Bindings: { transport: SSEHonoTransport } }>(); server.get("/sse", (c) => { return streamSSE(c, async (stream) => { c.env.transport.connectWithStream(stream); await bridge({ mcp, transport: c.env.transport, }); }); }); server.post("/messages", async (c) => { const transport = c.env.transport; if (!transport) { throw new Error("Transport not initialized"); } await transport.handlePostMessage(c); return c.text("ok"); }); server.onError((err, c) => { console.error(err); return c.body(err.message, 500); }); export class MyDurableObject extends DurableObject { transport?: SSEHonoTransport; constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); this.transport = new SSEHonoTransport("/messages", ctx.id.toString()); } async fetch(request: Request) { return server.fetch(request, { ...this.env, transport: this.transport, }); } } export default { async fetch( request: Request, env: { MY_DO: DurableObjectNamespace }, ctx: ExecutionContext, ): Promise { const url = new URL(request.url); const sessionId = url.searchParams.get("sessionId"); const namespace = env.MY_DO; let stub: DurableObjectStub; if (sessionId) stub = namespace.get(namespace.idFromString(sessionId)); else stub = namespace.get(namespace.newUniqueId()); return stub.fetch(request); }, }; ``` -------------------------------- ### Implement SSE Transport with Express for Muppet Server Source: https://www.muppet.dev/docs/server/concepts/transports This snippet illustrates how to configure `SSEServerTransport` for a Muppet server within a Node.js environment using `express`. It sets up an Express server to handle SSE connections on `/sse` and incoming messages on `/messages`, bridging the Muppet instance with the SSE transport. This enables real-time communication between the server and LLMs via Server-Sent Events. ```TypeScript import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; import { Hono } from "hono"; import { bridge, muppet, type MuppetEnv } from "muppet"; import express from "express"; const app = new Hono<{ Bindings: { muppet: MuppetEnv } }>(); // Define your tools, prompts, and resources here // ... const mcp = muppet(app, { name: "My Muppet", version: "1.0.0", }); let transport: SSEServerTransport | null = null; const server = express().use((req, res, next) => { console.log("Request received", req.url); next(); }); server.get("/sse", async (req, res) => { transport = new SSEServerTransport("/messages", res); bridge({ mcp, transport, }); }); server.post("/messages", (req, res) => { if (transport) { transport.handlePostMessage(req, res); } }); server.listen(3001); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.