### Install WebMCP with npx for MCP Clients Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Quickly install and configure WebMCP for various MCP clients (Claude Desktop, Cursor, Cline, Windsurf) using npx. This command automatically sets up the MCP client with the WebMCP server settings. Alternatively, use the --mcp flag for manual MCP server setup, which outputs configuration JSON. ```bash # Auto-install for Claude Desktop npx -y @jason.today/webmcp@latest --config claude # Auto-install for Cursor npx -y @jason.today/webmcp@latest --config cursor # Auto-install for Cline (VS Code extension) npx -y @jason.today/webmcp@latest --config cline # Auto-install for Windsurf npx -y @jason.today/webmcp@latest --config windsurf # Manual MCP server setup (outputs configuration JSON) npx -y @jason.today/webmcp@latest --mcp ``` -------------------------------- ### WebMCP Built-in Tools Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Describes the built-in tools available within WebMCP for token generation and schema definition. These tools are invoked via LLM prompts to assist in configuration and setup. ```javascript // _webmcp_get-token: Generates a registration token for website connection // _webmcp_define-mcp-tool: Helps define MCP tool schemas ``` -------------------------------- ### Register Tools and Prompts with WebMCP Source: https://github.com/jasonjmcghee/webmcp/blob/main/index.html Shows how to initialize a WebMCP instance and register various tools (calculator, echo, weather, time) and prompts (git-commit, explain-code) to extend agent capabilities. ```javascript window.webMCP = new WebMCP(); const mcp = window.webMCP; if (mcp) { mcp.registerTool('calculator', 'Performs basic math operations', { type: "object", properties: { a: {type: "number"}, b: {type: "number"}, operation: { type: "string", enum: ["add", "subtract", "multiply", "divide"] } } }, function (args) { const {operation, a, b} = args; let result; switch (operation) { case 'add': result = a + b; break; case 'subtract': result = a - b; break; case 'multiply': result = a * b; break; case 'divide': if (b === 0) throw new Error('Division by zero'); result = a / b; break; default: throw new Error(`Unknown operation: ${operation}`); } return { content: [{ type: "text", text: result.toString() }] }; }); mcp.registerPrompt('git-commit', 'Generate a Git commit message', [ { name: 'changes', description: 'Git diff or description of changes', required: true } ], function (args) { return { messages: [{ role: "user", content: { type: "text", text: `Generate a concise but descriptive commit message for these changes:\n\n${args.changes}` } }] }; }); } ``` -------------------------------- ### Registering Tools with WebMCP Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Demonstrates how to register various tools using the WebMCP instance. Tools require a name, description, JSON schema for arguments, and an execution function that returns MCP-compliant content. ```javascript const mcp = new WebMCP(); // Simple echo tool mcp.registerTool( 'echo', 'Echoes back the input message', { type: "object", properties: { message: { type: "string", description: "Message to echo back" } }, required: ["message"] }, function(args) { return { content: [{ type: "text", text: args.message }] }; } ); // Calculator tool with multiple operations mcp.registerTool( 'calculator', 'Performs basic math operations', { type: "object", properties: { a: { type: "number", description: "First operand" }, b: { type: "number", description: "Second operand" }, operation: { type: "string", enum: ["add", "subtract", "multiply", "divide"], description: "Mathematical operation to perform" } }, required: ["a", "b", "operation"] }, function(args) { const { operation, a, b } = args; let result; switch (operation) { case 'add': result = a + b; break; case 'subtract': result = a - b; break; case 'multiply': result = a * b; break; case 'divide': if (b === 0) throw new Error('Division by zero'); result = a / b; break; default: throw new Error(`Unknown operation: ${operation}`); } return { content: [{ type: "text", text: `Result: ${result}` }] }; } ); // Async tool with API call mcp.registerTool( 'weather', 'Get weather information for a location', { type: "object", properties: { location: { type: "string", description: "City name or coordinates" } }, required: ["location"] }, async function(args) { const response = await fetch(`https://api.weather.example/v1?q=${args.location}`); const data = await response.json(); return { content: [{ type: "text", text: `Weather for ${args.location}: ${data.condition}, ${data.temp}°C` }] }; } ); // Tool that interacts with the DOM mcp.registerTool( 'get-form-data', 'Retrieves data from a form on the page', { type: "object", properties: { formId: { type: "string", description: "ID of the form element" } }, required: ["formId"] }, function(args) { const form = document.getElementById(args.formId); if (!form) { return { content: [{ type: "text", text: `Form '${args.formId}' not found` }], isError: true }; } const formData = new FormData(form); const data = Object.fromEntries(formData.entries()); return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] }; } ); ``` -------------------------------- ### Initialize WebMCP and Register Custom Tool Source: https://github.com/jasonjmcghee/webmcp/blob/main/index.html JavaScript code demonstrating how to initialize the WebMCP library with custom options and register a new tool. The 'registerTool' function takes the tool name, description, arguments schema, and a callback function to execute when the tool is called. ```javascript // Initialize with custom options const mcp = new WebMCP({ color: '#4CAF50', position: 'top-right', size: '40px', padding: '15px' }); // Register custom tools mcp.registerTool( 'weather', 'Get weather information', { location: { type: "string" } }, function(args) { return { content: [{ type: "text", text: `Weather for ${args.location}: Sunny, 22°C` }] }; } ); ``` -------------------------------- ### HTML Structure and WebMCP Initialization Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Sets up the basic HTML for a web application and initializes the WebMCP library with custom configurations for color and position. It also includes placeholders for user interaction elements. ```html WebMCP Demo Application

My AI-Enabled App

``` -------------------------------- ### Register Static and Dynamic Resources in WebMCP Source: https://github.com/jasonjmcghee/webmcp/blob/main/index.html Demonstrates how to register a static resource for page content and a dynamic resource template for retrieving specific DOM elements by ID. These methods enable LLMs to interact with web page data through defined URI patterns. ```javascript // Register a resource for a specific file mcp.registerResource( 'page-content', 'Current page content', { uri: 'page://current', mimeType: 'text/html' }, function(uri) { return { contents: [ { uri: uri, mimeType: 'text/html', text: document.body.innerHTML } ] }; } ); // Register a resource template for dynamic data mcp.registerResource( 'element-content', 'Content of a specific DOM element by ID', { uriTemplate: 'element://{elementId}', mimeType: 'text/html' }, function(uri) { // Parse element ID from URI const elementId = uri.replace('element://', ''); const element = document.getElementById(elementId); if (!element) { throw new Error(`Element with ID "${elementId}" not found`); } return { contents: [ { uri: uri, mimeType: 'text/html', text: element.innerHTML } ] }; } ); ``` -------------------------------- ### Configure MCP Client with WebMCP Server Source: https://github.com/jasonjmcghee/webmcp/blob/main/index.html Configuration snippet for an MCP client to connect to a WebMCP server. This JSON object defines the 'webmcp' server, specifying the command to run ('npx') and its arguments to launch the WebMCP package. ```json { "mcpServers": { "webmcp": { "command": "npx", "args": [ "-y", "@jason.today/webmcp@latest", "--mcp" ] } } } ``` -------------------------------- ### WebSocket Server CLI Commands for WebMCP Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Manage the WebMCP WebSocket server using various command-line options. These commands allow starting/stopping the server, generating tokens, cleaning authorization data, specifying ports, and running in Docker mode. The server defaults to running as a daemon. ```bash # Start server as daemon (default behavior) npx @jason.today/webmcp # Start server in foreground for debugging npx @jason.today/webmcp --foreground # Generate a new registration token for website connection npx @jason.today/webmcp --new # Stop the running server daemon npx @jason.today/webmcp --quit # Clear all authorized tokens npx @jason.today/webmcp --clean # Specify custom port (default: 4797) npx @jason.today/webmcp --port 8080 # Run in Docker mode (server assumes container is running) npx @jason.today/webmcp --mcp --docker ``` -------------------------------- ### Register Code Explanation Prompt with WebMCP Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Registers a prompt template named 'explain-code' for explaining code snippets. It accepts 'code' (required) and an optional 'language' argument, returning a formatted prompt for the LLM. ```javascript // Code explanation prompt with optional language hint mcp.registerPrompt( 'explain-code', 'Explain how code works', [ { name: 'code', description: 'Code snippet to explain', required: true }, { name: 'language', description: 'Programming language (optional)', required: false } ], function(args) { const language = args.language || 'code'; return { messages: [ { role: "user", content: { type: "text", text: `Please explain how this ${language} code works:\n\n```${language}\n${args.code}\n```` } } ] }; } ); ``` -------------------------------- ### Server and Client Configuration Paths Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Defines the file system paths for WebMCP server configuration and the auto-detection paths for various MCP clients like Claude Desktop, Cursor, and Windsurf. ```javascript const CONFIG_DIR = '~/.webmcp'; const PID_FILE = '~/.webmcp/.webmcp-server.pid'; const ENV_FILE = '~/.webmcp/.env'; const TOKENS_FILE = '~/.webmcp/.webmcp-tokens.json'; ``` -------------------------------- ### Register MCP Resources Source: https://github.com/jasonjmcghee/webmcp/blob/main/index.html Demonstrates registering various resources including page content, specific DOM elements by ID, and user profile data. These handlers allow the MCP server to access browser-based information via URI schemes. ```javascript mcp.registerResource( 'page-content', 'Current page content', { uri: 'page://current', mimeType: 'text/html' }, function (uri) { return { contents: [ { uri: uri, mimeType: 'text/html', text: document.body.innerHTML } ] }; } ); mcp.registerResource( 'element-content', 'Content of a specific DOM element by ID', { uriTemplate: 'element://{elementId}', mimeType: 'text/html' }, function (uri) { const elementId = uri.replace('element://', ''); const element = document.getElementById(elementId); if (!element) { throw new Error(`Element with ID "${elementId}" not found`); } return { contents: [ { uri: uri, mimeType: 'text/html', text: element.innerHTML } ] }; } ); mcp.registerResource( 'user-data', 'Current user profile and preferences', { uri: 'user://profile', mimeType: 'application/json' }, function (uri) { const userData = document.getElementById('user-data').textContent; return { contents: [ { uri: uri, mimeType: 'application/json', text: userData } ] }; } ); ``` -------------------------------- ### Register Resources with WebMCP Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Registers static or templated resources to expose data to LLMs. The provideFn callback handles data retrieval, supporting both synchronous and asynchronous operations. ```javascript const mcp = new WebMCP(); // Static resource - current page content mcp.registerResource( 'page-content', 'Current page HTML content', { uri: 'page://current', mimeType: 'text/html' }, function(uri) { return { contents: [ { uri: uri, mimeType: 'text/html', text: document.body.innerHTML } ] }; } ); // Templated resource - dynamic element content by ID mcp.registerResource( 'element-content', 'Content of a specific DOM element by ID', { uriTemplate: 'element://{elementId}', mimeType: 'text/html' }, function(uri) { const elementId = uri.replace('element://', ''); const element = document.getElementById(elementId); if (!element) { throw new Error(`Element with ID "${elementId}" not found`); } return { contents: [ { uri: uri, mimeType: 'text/html', text: element.innerHTML } ] }; } ); // Async resource - fetch data from API mcp.registerResource( 'api-data', 'Data from backend API endpoint', { uriTemplate: 'api://{endpoint}', mimeType: 'application/json' }, async function(uri) { const endpoint = uri.replace('api://', ''); const response = await fetch(`/api/${endpoint}`); const data = await response.json(); return { contents: [ { uri: uri, mimeType: 'application/json', text: JSON.stringify(data, null, 2) } ] }; } ); ``` -------------------------------- ### Handle Sampling Requests in WebMCP Source: https://github.com/jasonjmcghee/webmcp/blob/main/index.html Demonstrates the JSON structure for a sampling request sent from the server to the WebMCP client. This request triggers a modal dialog for user input to facilitate agentic interactions. ```json { "method": "sampling/createMessage", "params": { "messages": [ { "role": "user", "content": { "type": "text", "text": "Write the appropriate DuckDB SQL to get the list of users joined with their accounts" } } ], "systemPrompt": "You are a helpful assistant.", "includeContext": "thisServer", "maxTokens": 100 } } ``` -------------------------------- ### POST registerTool Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Registers a new tool that LLMs can invoke. The tool requires a name, description, JSON schema for argument validation, and an execution function. ```APIDOC ## POST registerTool ### Description Registers a tool that LLMs can invoke to perform actions on the website. Tools accept arguments defined by a JSON schema and return results in MCP content format. ### Method POST ### Endpoint mcp.registerTool(name, description, schema, executeFn) ### Parameters #### Request Body - **name** (string) - Required - The unique identifier for the tool. - **description** (string) - Required - A description of what the tool does for the LLM. - **schema** (object) - Required - A JSON schema object defining the expected input arguments. - **executeFn** (function) - Required - The function to execute when the tool is called. Can be synchronous or return a Promise. ### Request Example { "name": "echo", "description": "Echoes back the input message", "schema": { "type": "object", "properties": { "message": { "type": "string" } }, "required": ["message"] } } ### Response #### Success Response (200) - **content** (array) - An array of content objects (type: "text") containing the tool output. #### Response Example { "content": [{ "type": "text", "text": "Hello World" }] } ``` -------------------------------- ### Website Integration with WebMCP Widget Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Integrate WebMCP into any website by including the `webmcp.js` script. The widget appears in the bottom right corner by default and handles connection management. Initialization can be done with default options or custom settings for color, position, size, padding, and inactivity timeout. ```html My WebMCP-Enabled Site ``` -------------------------------- ### WebMCP Prompt Registration: Analyze Page Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Registers an 'analyze-page' prompt with WebMCP. This prompt instructs the LLM to analyze the current page's content, sending the first 5000 characters of the body's text for analysis. ```javascript mcp.registerPrompt( 'analyze-page', 'Analyze the current page content', [], function() { return { messages: [{ role: 'user', content: { type: 'text', text: `Please analyze this page content and provide insights:\n\n${document.body.innerText.substring(0, 5000)}` } }] }; } ); ``` -------------------------------- ### Include WebMCP Script in HTML Source: https://github.com/jasonjmcghee/webmcp/blob/main/index.html Basic HTML snippet to include the WebMCP JavaScript library on a webpage. This line should be placed in the HTML to automatically initialize the WebMCP widget. ```html ``` -------------------------------- ### Register Text Summarization Prompt with WebMCP Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Registers a prompt template named 'summarize-text' for summarizing text content. It takes 'text' (required) and an optional 'length' argument to control the summary's verbosity, returning a tailored prompt. ```javascript // Text summarization with length control mcp.registerPrompt( 'summarize-text', 'Create a summary of text content', [ { name: 'text', description: 'Text content to summarize', required: true }, { name: 'length', description: 'Summary length: short, medium, or long', required: false } ], function(args) { const length = args.length || 'medium'; const lengthInstructions = { 'short': 'Keep the summary very concise, using no more than 2-3 sentences.', 'medium': 'Provide a moderate summary of about 4-6 sentences.', 'long': 'Create a comprehensive summary that covers all key points.' }; return { messages: [ { role: "user", content: { type: "text", text: `Please summarize the following text. ${lengthInstructions[length]}\n\n${args.text}` } } ] }; } ); ``` -------------------------------- ### Register a Git Commit Prompt Source: https://github.com/jasonjmcghee/webmcp/blob/main/index.html JavaScript code for registering a prompt named 'git-commit' using the WebMCP library. This prompt is designed to generate Git commit messages based on provided changes, demonstrating how to define prompt arguments and structure the LLM's message. ```javascript // Register a prompt for generating a Git commit message mcp.registerPrompt( 'git-commit', 'Generate a Git commit message', [ { name: 'changes', description: 'Git diff or description of changes', required: true } ], function(args) { return { messages: [ { role: "user", content: { type: "text", text: `Generate a concise but descriptive commit message for these changes:\n\n${args.changes}` } } ] }; } ); ``` -------------------------------- ### Manage UI Tab Switching Source: https://github.com/jasonjmcghee/webmcp/blob/main/index.html Handles tab navigation by toggling the 'active' class on tab elements and their corresponding content containers. ```javascript document.querySelectorAll('.tab').forEach(tab => { tab.addEventListener('click', function () { document.querySelectorAll('.tab').forEach(t => t.classList.remove('active')); this.classList.add('active'); document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active')); const tabId = this.getAttribute('data-tab'); document.getElementById(tabId + '-content').classList.add('active'); }); }); ``` -------------------------------- ### Register Git Commit Prompt with WebMCP Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Registers a prompt template named 'git-commit' for generating Git commit messages. It requires a 'changes' argument and returns a structured message array for the LLM. ```javascript const mcp = new WebMCP(); // Git commit message generator prompt mcp.registerPrompt( 'git-commit', 'Generate a Git commit message from changes', [ { name: 'changes', description: 'Git diff or description of changes', required: true } ], function(args) { return { messages: [ { role: "user", content: { type: "text", text: `Generate a concise but descriptive commit message for these changes:\n\n${args.changes}` } } ] }; } ); ``` -------------------------------- ### Register MCP Tool for Text Summarization Source: https://github.com/jasonjmcghee/webmcp/blob/main/index.html Registers a tool named 'summarize-text' that accepts text and length parameters. It returns a structured message object formatted for an AI assistant to process the summarization request. ```javascript t( 'summarize-text', 'Create a summary of text', [ { name: 'text', description: 'Text content to summarize', required: true }, { name: 'length', description: 'Desired length of summary (short, medium, long)', required: false } ], function (args) { const length = args.length || 'medium'; let lengthInstruction = ''; switch (length) { case 'short': lengthInstruction = 'Keep the summary very concise, using no more than 2-3 sentences.'; break; case 'medium': lengthInstruction = 'Provide a moderate summary of about 4-6 sentences.'; break; case 'long': lengthInstruction = 'Create a comprehensive summary that covers all key points.'; break; } return { messages: [ { role: "user", content: { type: "text", text: `Please summarize the following text. ${lengthInstruction}\n\n${args.text}` } } ] }; } ); ``` -------------------------------- ### WebMCP Tool Registration: Navigate Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Registers a 'navigate' tool with WebMCP, enabling an LLM to change the current page's URL. It takes a 'path' argument representing the relative URL to navigate to and updates the browser's location. ```javascript mcp.registerTool( 'navigate', 'Navigate to a URL on this site', { type: 'object', properties: { path: { type: 'string', description: 'Relative path to navigate to' } }, required: ['path'] }, function(args) { window.location.href = args.path; return { content: [{ type: 'text', text: `Navigating to ${args.path}` }] }; } ); ``` -------------------------------- ### WebSocket Server Message Schemas Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Defines the JSON structures for WebSocket communication, including tool registration, listing, execution, and resource management. These messages facilitate the interaction between the WebMCP widget and the server. ```javascript // Register a tool { type: 'registerTool', name: 'my-tool', description: 'Tool description', inputSchema: { type: 'object', properties: {} } }; // List tools { type: 'listTools', id: 'request-id' }; // Tool response { id: 'request-id', type: 'toolResponse', result: { content: [{ type: 'text', text: 'Result: 8' }] } }; // Register a resource { type: 'registerResource', name: 'my-resource', description: 'Resource description', uri: 'resource://data', mimeType: 'application/json' }; ``` -------------------------------- ### WebMCP Tool Registration: Fill Form Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Registers a 'fill-form' tool with WebMCP. This tool allows an LLM to fill input fields within a specified HTML form by providing the form ID and a key-value object of field names and their values. It includes error handling for non-existent forms. ```javascript mcp.registerTool( 'fill-form', 'Fill form fields with provided values', { type: 'object', properties: { formId: { type: 'string' }, values: { type: 'object' } }, required: ['formId', 'values'] }, function(args) { const form = document.getElementById(args.formId); if (!form) throw new Error('Form not found'); Object.entries(args.values).forEach(([name, value]) => { const input = form.querySelector(`[name="${name}"]`); if (input) input.value = value; }); return { content: [{ type: 'text', text: 'Form filled successfully' }] }; } ); ``` -------------------------------- ### Manage WebMCP WebSocket Connections Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Handles programmatic connection and disconnection to the WebMCP server using authentication tokens. Provides properties to monitor the current connection state. ```javascript const mcp = new WebMCP(); // Manual connection with token const connectionToken = 'eyJzZXJ2ZXIiOiJ3czovL2xvY2FsaG9zdDo0Nzk3IiwidG9rZW4iOiJhYmMxMjMifQ=='; mcp.connect(connectionToken); // Disconnect from server mcp.disconnect(); // Check connection status if (mcp.isConnected) { console.log('Connected to WebMCP server'); console.log('Current channel:', mcp.currentChannel); } ``` -------------------------------- ### WebMCP Resource Registration: Page State Source: https://context7.com/jasonjmcghee/webmcp/llms.txt Registers a 'page-state' resource with WebMCP. This resource provides the LLM with contextual information about the current page, including its URL, title, form IDs, and the current timestamp. ```javascript mcp.registerResource( 'page-state', 'Current page state and data', { uri: 'app://state', mimeType: 'application/json' }, function(uri) { return { contents: [{ uri: uri, mimeType: 'application/json', text: JSON.stringify({ url: window.location.href, title: document.title, forms: Array.from(document.forms).map(f => f.id), timestamp: new Date().toISOString() }, null, 2) }] }; } ); ``` -------------------------------- ### Simulate MCP Sampling Request Source: https://github.com/jasonjmcghee/webmcp/blob/main/index.html Triggers a simulated sampling request to the MCP server. This is used to test how the system handles message generation requests with specific system prompts and context. ```javascript mcp._handleCreateSamplingMessage({ id: "sample-" + Math.random().toString(36).substr(2, 9), messages: [ { role: "user", content: { type: "text", text: "Can you help me understand what MCP resources are?" } } ], systemPrompt: "You are a helpful assistant specialized in explaining MCP concepts.", includeContext: "thisServer", maxTokens: 500 }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.