### Install Dependencies and Start Development Server (pnpm) Source: https://github.com/sveltejs/mcp/blob/main/README.md This snippet outlines the commands to install project dependencies using pnpm, copy the example environment file, and start the development server. It's the primary setup for local development. ```shell pnpm i cp apps/mcp-remote/.env.example apps/mcp-remote/.env pnpm dev ``` -------------------------------- ### Start Drizzle Database Studio (pnpm) Source: https://github.com/sveltejs/mcp/blob/main/README.md Command to start the Drizzle Database Studio, a local tool for inspecting and managing the project's database. It provides a web interface for database operations. ```shell pnpm run db:studio ``` -------------------------------- ### Configure OpenCode for Local Svelte MCP Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/20-local-setup.md Guides through adding the local Svelte MCP server in OpenCode via interactive prompts. Selects 'Local' type and specifies the command. ```bash opencode mcp add ┌ Add MCP server │ ◇ Enter MCP server name │ svelte │ ◇ Select MCP server type │ Local │ ◆ Enter command to run │ npx -y @sveltejs/mcp ``` -------------------------------- ### Run Local Svelte MCP Server with npx Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/20-local-setup.md This is the core command to run the local MCP server using npx. It installs and runs the package without explicit global installation. ```bash npx -y @sveltejs/mcp ``` -------------------------------- ### Svelte MCP Project Setup and Development Commands Source: https://github.com/sveltejs/mcp/blob/main/CLAUDE.md Commands for setting up the Svelte MCP project, including installing dependencies, configuring environment variables, and running development servers. These commands leverage pnpm for package management. ```bash pnpm i cp .env.example .env # Set the VOYAGE_API_KEY for embeddings support in .env pnpm dev ``` ```bash pnpm dev - Start SvelteKit development server pnpm build - Build the application for production pnpm start - Run the MCP server (Node.js entry point) pnpm check - Run Svelte type checking pnpm check:watch - Run type checking in watch mode pnpm lint - Run prettier check and eslint pnpm format - Format code with prettier pnpm test - Run unit tests with vitest pnpm test:watch - Run tests in watch mode ``` ```bash pnpm db:push - Push schema changes to database pnpm db:generate - Generate migration files pnpm db:migrate - Run migrations pnpm db:studio - Open Drizzle Studio ``` -------------------------------- ### Configure Claude Desktop for Local Svelte MCP Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/20-local-setup.md Sets up the local Svelte MCP server in Claude Desktop's configuration file. Defines the command and its arguments. ```json { "mcpServers": { "svelte": { "command": "npx", "args": ["-y", "@sveltejs/mcp"] } } } ``` -------------------------------- ### Install tmcp and Adapters/Transports Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Installs the core tmcp package and optional schema library adapters (e.g., Zod) and transport layers (e.g., StdioTransport, HttpTransport). Users should select the adapter and transport that best suit their application needs. ```bash pnpm install tmcp # Choose your preferred schema library adapter pnpm install @tmcp/adapter-zod zod # Choose your preferred transport pnpm install @tmcp/transport-stdio # For CLI/desktop apps pnpm install @tmcp/transport-http # For web-based clients ``` -------------------------------- ### Configure Gemini CLI for Local Svelte MCP Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/20-local-setup.md Adds the local Svelte MCP server to Gemini CLI. This command directly integrates the server configuration. ```bash gemini mcp add -t stdio -s [scope] svelte npx -y @sveltejs/mcp ``` -------------------------------- ### Configure Zed for Local Svelte MCP Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/20-local-setup.md Configures the local Svelte MCP server in Zed via its settings panel. Involves adding a custom server with command and arguments. ```json { "svelte": { "command": "npx", "args": ["-y", "@sveltejs/mcp"] } } ``` -------------------------------- ### Run MCP Inspector (pnpm) Source: https://github.com/sveltejs/mcp/blob/main/README.md Command to launch the MCP inspector tool, which is used for local development and debugging. After running this, you can access the inspector via a provided URL. ```shell pnpm run inspect ``` -------------------------------- ### Setup STDIO Transport for Local MCP CLI Source: https://context7.com/sveltejs/mcp/llms.txt Sets up the Standard Input/Output (STDIO) transport for the local CLI version of the MCP server, allowing it to listen for commands. ```typescript #! /usr/bin/env node import { server } from '@sveltejs/mcp-server'; import { StdioTransport } from '@tmcp/transport-stdio'; const transport = new StdioTransport(server); transport.listen(); ``` -------------------------------- ### Configure Claude Code for Local Svelte MCP Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/20-local-setup.md Adds the local Svelte MCP server to Claude Code. Requires specifying a scope (user, project, or local). ```bash claude mcp add -t stdio -s [scope] svelte -- npx -y @sveltejs/mcp ``` -------------------------------- ### Svelte-Task Prompt Generation for AI (TypeScript) Source: https://context7.com/sveltejs/mcp/llms.txt Defines a prompt for an AI assistant to perform Svelte development tasks using MCP tools. It includes instructions on best practices, documentation access via `get_documentation`, and integration with `svelte-autofixer`. The prompt aims to guide the AI in creating Svelte components, fixing issues, and providing a playground link. ```typescript server.prompt( { name: 'svelte-task', title: 'Svelte-Task-Prompt', description: 'Instructs LLM on best practices for Svelte development with MCP tools.', schema: v.object({ task: v.pipe(v.string(), v.description('The task to be performed')), }), }, async ({ task }) => { const available_docs = await format_sections_list(); return { messages: [{ role: 'user', content: { type: 'text', text: `You are a Svelte expert tasked to build components for developers. Available documentation sections: ${available_docs} Instructions: 1. Use get_documentation tool to fetch relevant sections 2. Write Svelte code following best practices 3. Call svelte-autofixer on every component before sending to user 4. Fix all issues and suggestions returned by autofixer 5. Keep calling autofixer until no issues remain 6. After final code, ask user if they want a playground link Task: ${task}`, }, }], }; } ); // Usage in MCP client // Request: { name: 'svelte-task', arguments: { task: 'Create a counter component' } } // Response includes full prompt with available docs and step-by-step instructions ``` -------------------------------- ### MCP Tools Prompt for LLMs Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/10-introduction/10-overview.md A Markdown prompt outlining the available Svelte MCP tools for an LLM or agent. It details the purpose and usage of `list-sections`, `get-documentation`, `svelte-autofixer`, and `playground-link`, guiding the LLM on how to interact with the Svelte MCP server for documentation retrieval and code analysis. ```markdown You are able to use the Svelte MCP server, where you have access to comprehensive Svelte 5 and SvelteKit documentation. Here's how to use the available tools effectively: ## Available MCP Tools: ### 1. list-sections Use this FIRST to discover all available documentation sections. Returns a structured list with titles, use_cases, and paths. When asked about Svelte or SvelteKit topics, ALWAYS use this tool at the start of the chat to find relevant sections. ### 2. get-documentation Retrieves full documentation content for specific sections. Accepts single or multiple sections. After calling the list-sections tool, you MUST analyze the returned documentation sections (especially the use_cases field) and then use the get-documentation tool to fetch ALL documentation sections that are relevant for the user's task. ### 3. svelte-autofixer Analyzes Svelte code and returns issues and suggestions. You MUST use this tool whenever writing Svelte code before sending it to the user. Keep calling it until no issues or suggestions are returned. ### 4. playground-link Generates a Svelte Playground link with the provided code. After completing the code, ask the user if they want a playground link. Only call this tool after user confirmation and NEVER if code was written to files in their project. ``` -------------------------------- ### Configure Codex CLI for Local Svelte MCP Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/20-local-setup.md Adds the local Svelte MCP server configuration to Codex CLI's `config.toml` file. Specifies the command and arguments. ```toml [mcp_servers.svelte] command = "npx" args = ["-y", "@sveltejs/mcp"] ``` -------------------------------- ### Configure Remote MCP Server in GitHub Coding Agent Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/30-remote-setup.md Configures a remote MCP server for GitHub Coding Agent with specified type, URL, and tools. The configuration is provided in JSON format and includes 'type': 'http', 'url': 'https://mcp.svelte.dev/mcp', and 'tools': ['*']. ```json { "mcpServers": { "svelte": { "type": "http", "url": "https://mcp.svelte.dev/mcp", "tools": ["*"] } } } ``` -------------------------------- ### tmcp Server with Stdio Transport (JavaScript) Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Demonstrates setting up a tmcp server using the Zod adapter for schema validation and the StdioTransport for command-line interface or desktop applications. It includes registering a 'calculate' tool with a type-safe Zod schema and starting the server to listen for standard input/output. ```javascript import { McpServer } from 'tmcp'; import { ZodJsonSchemaAdapter } from '@tmcp/adapter-zod'; import { StdioTransport } from '@tmcp/transport-stdio'; import { z } from 'zod'; const adapter = new ZodJsonSchemaAdapter(); const server = new McpServer( { name: 'my-server', version: '1.0.0', description: 'My awesome MCP server', }, { adapter, capabilities: { tools: { listChanged: true }, prompts: { listChanged: true }, resources: { listChanged: true }, }, }, ); // Define a tool with type-safe schema server.tool( { name: 'calculate', description: 'Perform mathematical calculations', schema: z.object({ operation: z.enum(['add', 'subtract', 'multiply', 'divide']), a: z.number(), b: z.number(), }), }, async ({ operation, a, b }) => { switch (operation) { case 'add': return a + b; case 'subtract': return a - b; case 'multiply': return a * b; case 'divide': return a / b; } }, ); // Start the server with stdio transport const transport = new StdioTransport(server); transport.listen(); ``` -------------------------------- ### Get Svelte Documentation Content (TypeScript) Source: https://context7.com/sveltejs/mcp/llms.txt The `get-documentation` tool fetches the full documentation content for specified Svelte 5 or SvelteKit sections. It supports retrieving single sections or multiple sections via an array. The tool resolves section names or paths, fetches content using `fetch_with_timeout`, and handles cases where sections are not found. ```typescript server.tool( { name: 'get-documentation', description: 'Retrieves full documentation content for Svelte 5 or SvelteKit sections.', schema: v.object({ section: v.pipe( v.union([v.string(), v.array(v.string())]), v.description('Section name(s) to retrieve. Can search by title or path.') ), }), }, async ({ section }) => { let sections = Array.isArray(section) ? section : [section]; const available_sections = await get_sections(); const settled_results = await Promise.allSettled( sections.map(async (requested_section) => { const matched_section = available_sections.find( (s) => s.title.toLowerCase() === requested_section.toLowerCase() || s.slug === requested_section || s.url === requested_section ); if (matched_section) { const response = await fetch_with_timeout(matched_section.url); if (response.ok) { const content = await response.text(); return { success: true, content: `## ${matched_section.title}\n\n${content}` }; } } return { success: false, content: `## ${requested_section}\n\nError: Section not found.`, }; }) ); const results = settled_results.map((result) => result.status === 'fulfilled' ? result.value : { success: false, content: 'Error' } ); let final_text = results.map((r) => r.content).join('\n\n---\n\n'); return { content: [{ type: 'text', text: final_text }], }; } ); ``` -------------------------------- ### Setup HTTP Transport for SvelteKit MCP Source: https://context7.com/sveltejs/mcp/llms.txt Configures the HTTP transport for the SvelteKit web application version of the MCP server. It handles incoming requests, integrates with the database, and responds to MCP requests. ```typescript import { http_transport } from '$lib/mcp/index.js'; import { db } from '$lib/server/db/index.js'; export async function handle({ event, resolve }) { if (event.request.method === 'GET') { const accept = event.request.headers.get('accept'); if (accept && !accept.split(',').includes('text/event-stream')) { redirect(302, 'https://svelte.dev/docs/mcp/overview'); } } const mcp_response = await http_transport.respond(event.request, { db }); if (mcp_response && event.request.method === 'GET') { try { return mcp_response; } finally { try { await mcp_response.body?.cancel(); } catch { // ignore } } } return mcp_response ?? resolve(event); } ``` -------------------------------- ### Configure Remote MCP Server in Cursor Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/30-remote-setup.md Configures a remote MCP server in Cursor by adding a JSON entry to the MCP servers configuration file. The configuration includes the server name ('svelte') and its 'url'. ```json { "mcpServers": { "svelte": { "url": "https://mcp.svelte.dev/mcp" } } } ``` -------------------------------- ### tmcp Server with HTTP Transport (JavaScript) Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Illustrates setting up a tmcp server with HTTP transport, suitable for web-based clients. It uses the Zod adapter and integrates with a Bun HTTP server. The example shows how to handle incoming requests using the transport's `respond` method. ```javascript import { McpServer } from 'tmcp'; import { ZodJsonSchemaAdapter } from '@tmcp/adapter-zod'; import { HttpTransport } from '@tmcp/transport-http'; import { z } from 'zod'; const adapter = new ZodJsonSchemaAdapter(); const server = new McpServer(/* ... same server config ... */); // Add tools as above... // Create HTTP transport const transport = new HttpTransport(server); // Use with your preferred HTTP server (Bun example) Bun.serve({ port: 3000, async fetch(req) { const response = await transport.respond(req); if (response === null) { return new Response('Not Found', { status: 404 }); } return response; }, }); ``` -------------------------------- ### Configure Remote MCP Server in Codex CLI Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/30-remote-setup.md Enables the remote MCP client and configures a remote MCP server in Codex CLI by modifying the 'config.toml' file. This involves setting 'experimental_use_rmcp_client' to true and defining the server URL under the '[mcp_servers.svelte]' section. ```toml experimental_use_rmcp_client = true [mcp_servers.svelte] url = "https://mcp.svelte.dev/mcp" ``` -------------------------------- ### Add Remote MCP Server to Claude Code Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/30-remote-setup.md Adds the remote MCP server to Claude Code using the 'claude mcp add' command. Requires specifying the server type (http), a scope (user, project, or local), a name, and the remote server URL. ```bash claude mcp add -t http -s [scope] svelte https://mcp.svelte.dev/mcp ``` -------------------------------- ### Implement Tool with Complex Zod Schema Validation Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md This example demonstrates defining a 'create-user' tool that utilizes a complex, nested Zod schema for robust input validation. The schema includes nested user details, optional preferences, and an array of tags with a default value. The tool's handler function receives fully validated and typed input, ensuring data integrity before processing. ```javascript const complexSchema = z.object({ user: z.object({ name: z.string().min(1), email: z.string().email(), age: z.number().min(18).max(120), }), preferences: z .object({ theme: z.enum(['light', 'dark']), notifications: z.boolean(), }) .optional(), tags: z.array(z.string()).default([]), }); server.tool( { name: 'create-user', description: 'Create a new user with preferences', schema: complexSchema, }, async (input) => { // Input is fully typed and validated const { user, preferences, tags } = input; return await createUser(user, preferences, tags); }, ); ``` -------------------------------- ### Add Remote MCP Server to Gemini CLI Source: https://github.com/sveltejs/mcp/blob/main/documentation/docs/20-setup/30-remote-setup.md Adds the remote MCP server to Gemini CLI using the 'gemini mcp add' command. Similar to Claude Code, it requires specifying the server type (http), a scope, a name, and the remote server URL. ```bash gemini mcp add -t http -s [scope] svelte https://mcp.svelte.dev/mcp ``` -------------------------------- ### Define Tools with Zod and Valibot Schemas Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md This example shows how to register tools with the server, utilizing different schema validation libraries, Zod and Valibot, for distinct tools. It defines two tools, 'zod-tool' and 'valibot-tool', each with its own schema. The input for 'zod-tool' is an object with a 'name' string, and for 'valibot-tool', it's an object with an 'age' number. The output for both is a string. ```javascript // Use different schemas for different tools import { z } from 'zod'; import * as v from 'valibot'; server.tool( { name: 'zod-tool', schema: z.object({ name: z.string() }), }, async ({ name }) => `Hello ${name}`, ); server.tool( { name: 'valibot-tool', schema: v.object({ age: v.number() }), }, async ({ age }) => `Age: ${age}`, ); ``` -------------------------------- ### Initialize MCP Server with Valibot Adapter Source: https://context7.com/sveltejs/mcp/llms.txt Initializes the MCP Server with basic information, a Valibot JSON schema adapter, and defines capabilities. It also sets up context for database access. ```typescript import { ValibotJsonSchemaAdapter } from '@tmcp/adapter-valibot'; import { McpServer } from 'tmcp'; export const server = new McpServer( { name: 'Svelte MCP', version: '0.0.1', description: 'The official Svelte MCP server implementation', websiteUrl: 'https://mcp.svelte.dev', }, { adapter: new ValibotJsonSchemaAdapter(), capabilities: { tools: {}, prompts: {}, resources: {}, completions: {}, }, instructions: 'This is the official Svelte MCP server. It MUST be used whenever svelte development is involved.', }, ).withContext<{ db: LibSQLDatabase }>(); ``` -------------------------------- ### McpServer Constructor Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Initializes a new McpServer instance. The constructor takes server information and configuration options. ```APIDOC ## McpServer Constructor ### Description Initializes a new McpServer instance. The constructor takes server information and configuration options. ### Method `new McpServer(serverInfo, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **serverInfo** (object) - Required - Server metadata including `name`, `version`, and `description`. - **options** (object) - Required - Configuration object containing `adapter` and `capabilities`. - **options.adapter** (object) - Required - An instance of a schema adapter (e.g., `ZodJsonSchemaAdapter`). - **options.capabilities** (object) - Optional - Defines the server's supported capabilities (e.g., `tools`, `prompts`, `resources`) and their change tracking status (e.g., `listChanged: true`). ### Request Example ```javascript import { McpServer } from 'tmcp'; import { ZodJsonSchemaAdapter } from '@tmcp/adapter-zod'; const adapter = new ZodJsonSchemaAdapter(); const server = new McpServer( { name: 'my-server', version: '1.0.0', description: 'My awesome MCP server', }, { adapter, capabilities: { tools: { listChanged: true }, prompts: { listChanged: true }, resources: { listChanged: true }, }, } ); ``` ### Response #### Success Response (200) N/A (Constructor does not return a value, it initializes an object) #### Response Example N/A ``` -------------------------------- ### McpServer: Registering a Prompt (JavaScript) Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Demonstrates registering a prompt template with McpServer. The `prompt` method allows defining a prompt's name, description, optional schema for input, and a `complete` function for generating suggestions. The handler function returns the messages for the prompt. ```javascript server.prompt( { name: 'prompt-name', description: 'Prompt description', schema: yourSchema, // optional complete: (arg, context) => ['completion1', 'completion2'] // optional }, async (input) => { // Prompt implementation return { messages: [...] }; } ); ``` -------------------------------- ### McpServer: Registering a Tool (JavaScript) Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Shows how to register a new tool with the McpServer. The `tool` method accepts a definition object, including name, description, and an optional schema for input validation, along with an asynchronous handler function that executes the tool's logic. ```javascript server.tool( { name: 'tool-name', description: 'Tool description', schema: yourSchema, // optional }, async (input) => { // Tool implementation return result; }, ); ``` -------------------------------- ### List Svelte Documentation Sections (TypeScript) Source: https://context7.com/sveltejs/mcp/llms.txt The `list-sections` tool retrieves and formats a list of available Svelte 5 and SvelteKit documentation sections. It includes metadata like 'use_cases' for relevance matching and outputs a formatted text string. No external dependencies beyond internal utility functions are explicitly shown. ```typescript server.tool( { name: 'list-sections', description: 'Lists all available Svelte 5 and SvelteKit documentation sections. Each section includes use_cases describing when it would be useful.', }, async () => { const formatted_sections = await format_sections_list(); return { content: [{ type: 'text', text: `${SECTIONS_LIST_INTRO}\n\n${formatted_sections}\n\n${SECTIONS_LIST_OUTRO}`, }], }; } ); // Example output format: // * title: $state rune, use_cases: interactive components, state management, always, path: svelte/reactivity/$state // * title: Routing, use_cases: multi-page apps, navigation, e-commerce, blog, path: sveltekit/routing/basics ``` -------------------------------- ### McpServer: Registering a Resource (JavaScript) Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Illustrates how to register a static resource with McpServer. The `resource` method takes a definition including name, description, and a URI pointing to the resource. The handler function is responsible for returning the resource's contents. ```javascript server.resource( { name: 'resource-name', description: 'Resource description', uri: 'file://path/to/resource' }, async (uri, params) => { // Resource implementation return { contents: [...] }; } ); ``` -------------------------------- ### Create Resource Template with Completion Logic Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md This snippet illustrates how to define a resource template named 'user-profile' for retrieving user profile information. It includes a 'complete' function to provide suggestions for the 'userId' parameter, enhancing user experience. The template uses a URI pattern 'users/{userId}/profile' and returns user data in a structured format. ```javascript server.template( { name: 'user-profile', description: 'Get user profile by ID', uri: 'users/{userId}/profile', complete: (arg, context) => { // Provide completions for userId parameter return ['user1', 'user2', 'user3']; }, }, async (uri, params) => { const user = await getUserById(params.userId); return { contents: [ { uri, mimeType: 'application/json', text: JSON.stringify(user), }, ], }; }, ); ``` -------------------------------- ### McpServer: Registering a URI Template (JavaScript) Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Shows how to register a URI template for dynamic resources with McpServer. The `template` method defines a named template with a URI pattern (which can include parameters like `{id}`). It also supports an optional `complete` function for generating parameter values and a handler to process the dynamic resource. ```javascript server.template( { name: 'template-name', description: 'Template description', uri: 'file://path/{id}/resource', complete: (arg, context) => ['id1', 'id2'] // optional }, async (uri, params) => { // Template implementation using params.id return { contents: [...] }; } ); ``` -------------------------------- ### Generate Svelte Playground Link (TypeScript) Source: https://context7.com/sveltejs/mcp/llms.txt The `playground-link` tool generates compressed Svelte Playground URLs. It supports multiple files, Tailwind CSS integration, and requires an `App.svelte` file as the entry point. The tool compresses the configuration and encodes it into the URL's hash fragment. ```typescript server.tool( { name: 'playground-link', description: 'Generates a Playground link given Svelte code.', schema: v.object({ name: v.pipe(v.string(), v.description('The name of the Playground')), tailwind: v.pipe(v.boolean(), v.description('If code requires Tailwind CSS')), files: v.pipe( v.record(v.string(), v.string()), v.description("Object with filenames as keys and content as values") ), }), outputSchema: v.object({ url: v.string() }), }, async ({ files, name, tailwind }) => { const playground_files = Object.entries(files).map(([filename, contents]) => ({ type: 'file', name: filename, basename: filename.replace(/^.*[\\/]/, ''), contents, text: true, })); if (!files['App.svelte']) { return { isError: true, content: [{ type: 'text', text: JSON.stringify({ error: 'Files must contain App.svelte as entry point' }), }], }; } const playground_config = { name, tailwind: tailwind ?? false, files: playground_files, }; const playground_url = new URL('https://svelte.dev/playground'); playground_url.hash = await compress_and_encode_text(JSON.stringify(playground_config)); return { content: [{ type: 'text', text: JSON.stringify({ url: playground_url.toString() }) }], structuredContent: { url: playground_url.toString() }, }; } ); ``` -------------------------------- ### Register Prompt: server.prompt() Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Registers a prompt template with the MCP server. Prompt templates can be used to generate messages for language models. ```APIDOC ## Register Prompt: server.prompt() ### Description Registers a prompt template with the MCP server. Prompt templates can be used to generate messages for language models. Input can be validated using a schema, and a `complete` function can provide suggestions. ### Method `server.prompt(definition, handler)` ### Endpoint N/A (Method of the McpServer instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **definition** (object) - Required - Defines the prompt's metadata. - **definition.name** (string) - Required - The unique name of the prompt. - **definition.description** (string) - Required - A description of the prompt. - **definition.schema** (object) - Optional - A validation schema for the prompt's input. - **definition.complete** (function) - Optional - A function that returns a list of possible completions for the prompt input, useful for autocompletion. - **handler** (function) - Required - An asynchronous function that generates the prompt messages. It receives the validated input and context, and should return an object with a `messages` array. ### Request Example ```javascript // Assuming 'server' is an instance of McpServer server.prompt( { name: 'summarize-text', description: 'Summarize the provided text.', // schema: z.object({ text: z.string() }), // Example schema // complete: async (arg, context) => ['short', 'detailed'], // Example completions }, async (input, context) => { // Logic to generate messages based on input and context return { messages: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: `Please summarize the following text: ${input.text}` }, ], }; } ); ``` ### Response #### Success Response (200) N/A (This method registers a handler and does not directly return a response to a client request in this context.) #### Response Example N/A ``` -------------------------------- ### Register Template: server.template() Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Registers a URI template for dynamic resources with the MCP server. Templates allow for parameterized resource URIs. ```APIDOC ## Register Template: server.template() ### Description Registers a URI template for dynamic resources with the MCP server. Templates allow for parameterized resource URIs, enabling clients to request resources with specific identifiers. ### Method `server.template(definition, handler)` ### Endpoint N/A (Method of the McpServer instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **definition** (object) - Required - Defines the template's metadata. - **definition.name** (string) - Required - The unique name of the template. - **definition.description** (string) - Required - A description of the template. - **definition.uri** (string) - Required - The URI template string (e.g., `file://path/{id}/resource`). - **definition.complete** (function) - Optional - A function that provides possible values for template parameters, useful for autocompletion. - **handler** (function) - Required - An asynchronous function that processes the request for a dynamic resource. It receives the URI and parameters extracted from the template, and should return an object with a `contents` property. ### Request Example ```javascript // Assuming 'server' is an instance of McpServer server.template( { name: 'user-profile', description: 'Get user profile by ID', uri: 'api://users/{userId}/profile', // complete: async (arg, context) => ['user1', 'user2'], // Example completions for userId }, async (uri, params) => { const userId = params.userId; // Logic to fetch user profile based on userId const userProfile = { id: userId, name: 'Example User' }; return { contents: JSON.stringify(userProfile) }; } ); ``` ### Response #### Success Response (200) N/A (This method registers a handler and does not directly return a response to a client request in this context.) #### Response Example N/A ``` -------------------------------- ### Register Tool: server.tool() Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Registers a tool with the MCP server. Tools are functions that can be executed by clients. ```APIDOC ## Register Tool: server.tool() ### Description Registers a tool with the MCP server. Tools are functions that can be executed by clients. Optionally, a schema can be provided for input validation. ### Method `server.tool(definition, handler)` ### Endpoint N/A (Method of the McpServer instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **definition** (object) - Required - Defines the tool's metadata. - **definition.name** (string) - Required - The unique name of the tool. - **definition.description** (string) - Required - A description of what the tool does. - **definition.schema** (object) - Optional - A validation schema for the tool's input (e.g., Zod schema). - **handler** (function) - Required - An asynchronous function that executes the tool's logic. It receives the validated input as an argument and should return the result. ### Request Example ```javascript // Assuming 'server' is an instance of McpServer import { z } from 'zod'; server.tool( { name: 'calculate', description: 'Perform mathematical calculations', schema: z.object({ operation: z.enum(['add', 'subtract', 'multiply', 'divide']), a: z.number(), b: z.number(), }), }, async ({ operation, a, b }) => { switch (operation) { case 'add': return a + b; case 'subtract': return a - b; case 'multiply': return a * b; case 'divide': return a / b; } } ); ``` ### Response #### Success Response (200) N/A (This method registers a handler and does not directly return a response to a client request in this context.) #### Response Example N/A ``` -------------------------------- ### Register Resource: server.resource() Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md Registers a static resource with the MCP server. Resources can be files or other static assets. ```APIDOC ## Register Resource: server.resource() ### Description Registers a static resource with the MCP server. Resources are typically files or data that can be served to clients. ### Method `server.resource(definition, handler)` ### Endpoint N/A (Method of the McpServer instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **definition** (object) - Required - Defines the resource's metadata. - **definition.name** (string) - Required - The unique name of the resource. - **definition.description** (string) - Required - A description of the resource. - **definition.uri** (string) - Required - The URI identifying the resource (e.g., `file://path/to/resource`). - **handler** (function) - Required - An asynchronous function that fetches and returns the resource content. It receives the resource URI and optional parameters, and should return an object with a `contents` property. ### Request Example ```javascript // Assuming 'server' is an instance of McpServer server.resource( { name: 'logo.png', description: 'Company logo image', uri: 'file:///path/to/your/logo.png', }, async (uri, params) => { // Logic to read and return the file content const fileContent = await fetch(uri).then(res => res.arrayBuffer()); return { contents: new Uint8Array(fileContent) }; } ); ``` ### Response #### Success Response (200) N/A (This method registers a handler and does not directly return a response to a client request in this context.) #### Response Example N/A ``` -------------------------------- ### Implement svelte-autofixer Tool Source: https://context7.com/sveltejs/mcp/llms.txt Defines and registers the 'svelte-autofixer' tool with the MCP server. This tool analyzes Svelte code, identifies issues, and provides suggestions for fixes based on compilation errors, ESLint rules, and custom logic. It requires code, an optional filename, and the desired Svelte version as input. ```typescript import { server } from '@sveltejs/mcp-server'; server.tool( { name: 'svelte-autofixer', title: 'Svelte Autofixer', description: 'Given a svelte component or module returns a list of suggestions to fix any issues it has.', schema: v.object({ code: v.string(), desired_svelte_version: v.pipe( v.union([v.string(), v.number()]), v.description('The desired svelte version (4 or 5)') ), filename: v.pipe( v.optional(v.string()), v.description('The filename of the component with .svelte extension') ), }), outputSchema: v.object({ issues: v.array(v.string()), suggestions: v.array(v.string()), require_another_tool_call_after_fixing: v.boolean(), }), }, async ({ code, filename, desired_svelte_version }) => { const content = { issues: [], suggestions: [], require_another_tool_call_after_fixing: false }; try { const name = filename ? basename(filename) : 'Component.svelte'; add_compile_issues(content, code, +desired_svelte_version, name); add_autofixers_issues(content, code, +desired_svelte_version, name); await add_eslint_issues(content, code, +desired_svelte_version, name); } catch (e) { content.issues.push(`${e.message} at line ${e.start?.line}`); } if (content.issues.length > 0 || content.suggestions.length > 0) { content.require_another_tool_call_after_fixing = true; } return { content: [{ type: 'text', text: JSON.stringify(content) }], structuredContent: content, }; } ); ``` -------------------------------- ### Process MCP Request with Server Source: https://github.com/sveltejs/mcp/blob/main/docs/tmcp.md This snippet demonstrates how to process an incoming MCP request using the server's receive function. It takes a JSON RPC request and returns a response. The primary input is a JSON RPC request object, and the output is a server response. ```javascript const response = server.receive(jsonRpcRequest); ``` -------------------------------- ### Parse Svelte Components with AST and Scope Analysis (TypeScript) Source: https://context7.com/sveltejs/mcp/llms.txt Parses Svelte components to generate an AST, perform scope analysis, and detect runes. It leverages svelte-eslint-parser and supports TypeScript via @typescript-eslint/parser. The function returns an object with properties for AST, tokens, scope manager, visitor keys, and methods to retrieve all scopes, variables, references, and to find specific references. It also includes a utility to check if a call is a rune. ```typescript import { parseForESLint as svelte_eslint_parse } from 'svelte-eslint-parser'; import ts_parser from '@typescript-eslint/parser'; export function parse(code: string, file_path: string) { const parsed = svelte_eslint_parse(code, { filePath: file_path, parser: { ts: ts_parser, typescript: ts_parser }, }); function collect_scopes(scope, acc = []) { acc.push(scope); for (const child of scope.childScopes ?? []) collect_scopes(child, acc); return acc; } const { ast: { tokens, ...ast } } = parsed; delete parsed.ast.tokens; return { ast, tokens, scope_manager: parsed.scopeManager, visitor_keys: parsed.visitorKeys, get all_scopes() { return collect_scopes(parsed.scopeManager.globalScope); }, get all_variables() { return this.all_scopes.flatMap((s) => s.variables ?? []); }, get all_references() { return this.all_scopes.flatMap((s) => s.references ?? []); }, find_reference_by_id(id) { return this.all_references.find((r) => r.identifier === id); }, is_rune(call, rune) { if (call.callee.type !== 'Identifier' && call.callee.type !== 'MemberExpression') return false; const id = call.callee.type === 'Identifier' ? call.callee : call.callee.object; const property = call.callee.type === 'MemberExpression' ? call.callee.property : null; const callee_text = `${id.name}${property ? `.${property.name}` : ''}`; if (rune && !rune.includes(callee_text)) return false; const reference = this.find_reference_by_id(id); if (!reference) return false; const variable = reference.resolved; return variable && variable.defs.length === 0; }, }; } // Usage example const code = ` `; const parsed = parse(code, 'Counter.svelte'); console.log(parsed.all_variables.map(v => v.name)); // ['count'] console.log(parsed.all_scopes.length); // Multiple scopes ``` -------------------------------- ### Autofixer for State Mutations in Svelte Effects (TypeScript) Source: https://context7.com/sveltejs/mcp/llms.txt Implements the AST visitor pattern to detect and suggest fixes for anti-patterns, specifically state mutations within Svelte effects. It identifies assignments or updates to state variables inside $effect calls and suggests using $derived instead. It also warns about calling arbitrary functions inside $effect. ```typescript import type { AssignmentExpression, CallExpression, Identifier, UpdateExpression } from 'estree'; export const assign_in_effect: Autofixer = { UpdateExpression: assign_or_update_visitor, AssignmentExpression: assign_or_update_visitor, CallExpression: call_expression_visitor, }; function assign_or_update_visitor( node: UpdateExpression | AssignmentExpression, { state, path, next } ) { const in_effect = path.findLast( (n) => n.type === 'CallExpression' && state.parsed.is_rune(n, ['$effect', '$effect.pre']) ); if (in_effect) { const variable = node.type === 'UpdateExpression' ? node.argument : node.left; if (variable.type === 'Identifier') { const reference = state.parsed.find_reference_by_id(variable); const definition = reference?.resolved?.defs[0]; if (definition?.type === 'Variable') { const init = definition.node.init; if (init?.type === 'CallExpression' && state.parsed.is_rune(init, ['$state', '$derived'])) { state.output.suggestions.push( `Variable "${variable.name}" assigned in $effect. Consider using $derived.` ); } } } } next(); } function call_expression_visitor( node: CallExpression, { state, path, next } ) { const in_effect = path.findLast( (n) => n.type === 'CallExpression' && state.parsed.is_rune(n, ['$effect']) ); if (in_effect) { const function_name = node.callee.type === 'Identifier' ? ``${node.callee.name}`` : 'a function'; state.output.suggestions.push( `Calling ${function_name} inside $effect. Check if it reassigns state.` ); } next(); } // Usage with walker const code = ` `; const parsed = parse(code, 'Component.svelte'); const output = { issues: [], suggestions: [] }; walk(parsed.ast, { parsed, output }, assign_in_effect); console.log(output.suggestions); // ['Variable "count" assigned in $effect. Consider using $derived.'] ``` -------------------------------- ### Detect Svelte Compilation Issues (TypeScript) Source: https://context7.com/sveltejs/mcp/llms.txt Detects syntax and semantic errors in Svelte components and modules using the Svelte compiler. It can also transpile TypeScript modules to identify issues within them. The function populates a content object with detected issues and suggestions. It supports specifying the desired Svelte version to enable/disable rune support during compilation. ```typescript import { compile as compile_component, compileModule } from 'svelte/compiler'; import { extname } from 'path'; import ts from 'ts-blank-space'; export function add_compile_issues( content: { issues: string[]; suggestions: string[] }, code: string, desired_svelte_version: number, filename = 'Component.svelte', ) { let compile = compile_component; const extension = extname(filename); if (extension !== '.svelte') { compile = compileModule; // Transpile TypeScript modules while preserving positions if (extension === '.ts') { code = ts(code, (node) => { content.issues.push( `Invalid TypeScript: ${node.getText()} at ${node.getStart()}` ); }); } } const compilation_result = compile(code, { filename, generate: false, runes: desired_svelte_version >= 5, }); for (const warning of compilation_result.warnings) { content.issues.push( `${warning.message} at line ${warning.start?.line}, column ${warning.start?.column}` ); } } // Usage example const content = { issues: [], suggestions: [] }; const code = ` `; add_compile_issues(content, code, 5, 'Counter.svelte'); console.log(content.issues); // ['Expected ) at line 3, column 25'] ```