{"id":48594180,"url":"https://github.com/up2itnow0822/webmcp-sdk","last_synced_at":"2026-04-08T20:55:31.190Z","repository":{"id":339714475,"uuid":"1162671980","full_name":"up2itnow0822/webmcp-sdk","owner":"up2itnow0822","description":"Full WebMCP developer toolkit — core, React, security, testing. Build agent-ready websites with navigator.modelContext","archived":false,"fork":false,"pushed_at":"2026-04-06T21:22:26.000Z","size":231,"stargazers_count":1,"open_issues_count":2,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-08T20:55:28.844Z","etag":null,"topics":["ai-agents","browser","mcp","sdk","web","webmcp"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/webmcp-sdk","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/up2itnow0822.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-20T14:54:50.000Z","updated_at":"2026-04-06T21:21:34.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/up2itnow0822/webmcp-sdk","commit_stats":null,"previous_names":["up2itnow0822/webmcp-sdk","up2itnow/webmcp-sdk"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/up2itnow0822/webmcp-sdk","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/up2itnow0822%2Fwebmcp-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/up2itnow0822%2Fwebmcp-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/up2itnow0822%2Fwebmcp-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/up2itnow0822%2Fwebmcp-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/up2itnow0822","download_url":"https://codeload.github.com/up2itnow0822/webmcp-sdk/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/up2itnow0822%2Fwebmcp-sdk/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31573788,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-08T14:31:17.711Z","status":"ssl_error","status_checked_at":"2026-04-08T14:31:17.202Z","response_time":54,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-agents","browser","mcp","sdk","web","webmcp"],"created_at":"2026-04-08T20:55:30.295Z","updated_at":"2026-04-08T20:55:31.176Z","avatar_url":"https://github.com/up2itnow0822.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"![CI](https://github.com/up2itnow0822/webmcp-sdk/actions/workflows/ci.yml/badge.svg)\n![CodeQL](https://github.com/up2itnow0822/webmcp-sdk/actions/workflows/codeql.yml/badge.svg)\n![npm](https://img.shields.io/npm/v/webmcp-sdk)\n![License](https://img.shields.io/npm/l/webmcp-sdk)\n\n# webmcp-sdk 🌐🤖\n\n**Make any website agent-ready with [WebMCP](https://webmachinelearning.github.io/webmcp/) in minutes.**\n\nThe developer toolkit for the W3C Web Model Context Protocol — the standard that turns websites into structured tools for AI agents. No screen scraping. No Puppeteer scripts. Your frontend JavaScript becomes the agent interface.\n\nZero dependencies. Full TypeScript. Production CI verified.\n\n---\n\n## Why Now?\n\nChrome 146 shipped `navigator.modelContext` in February 2026. It's flag-gated today — but this is the Canary that ships to 3 billion users. When it graduates, every website that isn't already WebMCP-ready gets left behind.\n\nMicrosoft co-authored the spec. W3C is fast-tracking it. Formal announcement is expected at Google I/O mid-2026. The window to build before mainstream coverage closes is right now.\n\n`webmcp-sdk` is the Express to Chrome's HTTP — the implementation layer that makes the low-level API actually usable.\n\n---\n\n## What You Get\n\n- 🏗️ **TypeScript-first** — Full types for the WebMCP API surface\n- ⚡ **Builder pattern** — Fluent API, no boilerplate\n- 🛡️ **Security middleware** — Rate limiting, input sanitization, audit logging\n- ⚛️ **React hooks** — `useWebMCPTool()` registers on mount, cleans up on unmount\n- 🧪 **Testing utilities** — Mock browser context, test runner, quality scorer\n- ✅ **Input validation** — JSON Schema validation before your handler runs\n- 🔒 **Confirmation guards** — Destructive actions require user approval\n- 🔍 **Express auto-discovery** — Agents find your tools automatically, zero config\n\n---\n\n\n## Security Notice\n\nThis SDK exposes tools to AI agents via the W3C WebMCP API. Review the [OWASP MCP Top 10](https://owasp.org/www-project-mcp-top-10/) before deploying to production. Key risks to evaluate:\n\n- **Tool injection:** Validate and sanitize all tool inputs before processing\n- **Excessive data exposure:** Return only the data an agent needs, not full database records\n- **Privilege escalation:** Scope each tool to the minimum permissions required\n\nSee the [Security Middleware](#security-middleware) section below for built-in protections.\n\n## Install\n\n```bash\nnpm install webmcp-sdk\n```\n\n---\n\n## Quick Start — Register a Tool\n\n```typescript\nimport { createKit, defineTool } from 'webmcp-sdk';\n\nconst kit = createKit({ prefix: 'myshop' });\n\nkit.register(defineTool(\n  'search',\n  'Search products by keyword. Returns matching products with prices and availability.',\n  {\n    type: 'object',\n    properties: {\n      query: { type: 'string', description: 'Search keyword or phrase' },\n      category: { type: 'string', enum: ['electronics', 'clothing', 'home'] },\n      maxResults: { type: 'number', minimum: 1, maximum: 50 },\n    },\n    required: ['query'],\n  },\n  async ({ query, category, maxResults = 10 }) =\u003e {\n    const results = await yourSearchFunction(query, { category, limit: maxResults });\n    return { results, total: results.length };\n  }\n));\n```\n\nWhen an AI agent visits your site in Chrome 146+, it sees `myshop.search` as a callable, typed tool. That's it.\n\n---\n\n## Builder Pattern\n\n```typescript\nimport { createKit, tool } from 'webmcp-sdk';\n\nconst kit = createKit();\n\nkit.register(\n  tool('add-to-cart')\n    .description('Add a product to the shopping cart by product ID')\n    .input({\n      type: 'object',\n      properties: {\n        productId: { type: 'string', description: 'Product ID' },\n        quantity: { type: 'number', minimum: 1, maximum: 99 },\n      },\n      required: ['productId'],\n    })\n    .annotate({ destructiveHint: false, confirmationHint: false })\n    .handle(async ({ productId, quantity = 1 }) =\u003e {\n      return await addToCart(productId, quantity);\n    })\n);\n```\n\n---\n\n## Server-Side Auto-Discovery (Express)\n\nAny agent that hits your server instantly knows where to find your MCP tools — no docs, no config.\n\n### Zero Config\n\n```typescript\nimport express from 'express';\nimport { webmcpDiscovery } from 'webmcp-sdk/middleware/express';\n\nconst app = express();\napp.use(webmcpDiscovery());    // agents auto-discover your /mcp endpoint\n```\n\nEvery response gets:\n```\nLink: \u003c/mcp\u003e; rel=\"mcp-manifest\", \u003c/mcp/tools\u003e; rel=\"mcp-tools\"\nMCP-Version: 1.0\nMCP-Capabilities: tools\n```\n\n### Full Auto-Setup (headers + manifest endpoint)\n\n```typescript\nimport { webmcpAutoSetup } from 'webmcp-sdk/middleware/express';\n\napp.use(webmcpAutoSetup({\n  serverName: 'My API',\n  tools: [\n    { name: 'search', description: 'Search the product catalog' },\n    { name: 'checkout', description: 'Place an order' },\n  ],\n  resources: [\n    { uri: '/docs', name: 'API Documentation' },\n  ],\n}));\n// → Injects discovery headers on all responses\n// → GET /mcp  returns full manifest JSON\n// → GET /mcp/tools\n// → GET /mcp/resources\n```\n\n### Custom Options\n\n```typescript\napp.use(webmcpDiscovery({\n  manifestPath: '/api/mcp',\n  capabilities: ['tools', 'resources', 'prompts'],\n  version: '1.0',\n  serverName: 'My App',\n  onlyOnSuccess: true,   // skip 4xx/5xx (default: true)\n}));\n```\n\n### FastAPI\n\n```python\nfrom fastapi import FastAPI\nfrom webmcp_sdk.middleware import WebMCPDiscoveryMiddleware\n\napp = FastAPI()\napp.add_middleware(WebMCPDiscoveryMiddleware)\n```\n\nWith options:\n\n```python\napp.add_middleware(\n    WebMCPDiscoveryMiddleware,\n    manifest_path='/mcp',\n    capabilities=['tools', 'resources'],\n    server_name='My API',\n    only_on_success=True,\n)\n```\n\nFull auto-setup:\n\n```python\nfrom webmcp_sdk.middleware import WebMCPAutoSetupMiddleware\n\napp.add_middleware(\n    WebMCPAutoSetupMiddleware,\n    server_name='My API',\n    tools=[{'name': 'search', 'description': 'Search products'}],\n)\n```\n\n---\n\n## React Integration\n\n```typescript\nimport { useWebMCPTool, useWebMCPAvailable } from 'webmcp-sdk/react';\n```\n\n```tsx\nfunction ProductSearch() {\n  useWebMCPTool({\n    name: 'search',\n    description: 'Search products in the catalog',\n    inputSchema: {\n      type: 'object',\n      properties: { query: { type: 'string', description: 'Search term' } },\n      required: ['query'],\n    },\n    handler: async ({ query }) =\u003e {\n      const results = await searchProducts(query);\n      return { results, count: results.length };\n    },\n  });\n\n  return \u003cdiv\u003eSearch is agent-ready! 🤖\u003c/div\u003e;\n}\n\nfunction App() {\n  const isAgentReady = useWebMCPAvailable();\n  return (\n    \u003cdiv\u003e\n      {isAgentReady \u0026\u0026 \u003cspan\u003e🟢 WebMCP Active\u003c/span\u003e}\n      \u003cProductSearch /\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n### Available Hooks\n\n| Hook | Purpose |\n|------|---------|\n| `useWebMCPTool(tool)` | Register a single tool (auto-cleanup on unmount) |\n| `useWebMCPTools(tools[])` | Register multiple tools at once |\n| `useWebMCPAvailable()` | Check if WebMCP is available in the browser |\n| `useWebMCPLog(maxEntries?)` | Track agent tool invocations for debugging |\n| `useWebMCPKit(config?)` | Get the shared Kit instance for advanced usage |\n\n---\n\n## Security\n\n```typescript\nimport { withSecurity, withConfirmation } from 'webmcp-sdk/security';\n\n// Rate limit + sanitize + block patterns + audit\nconst secureTool = withSecurity(myTool, {\n  rateLimit: { maxInvocations: 10, windowMs: 60_000 },\n  sanitize: { stripHtml: true, maxStringLength: 5000 },\n  blockedPatterns: ['\u003cscript', 'javascript:', 'data:text/html'],\n  audit: true,\n  onAudit: (event) =\u003e analytics.track('agent_tool_call', event),\n});\n\n// Require user confirmation for destructive actions\nconst safeDeleteTool = withConfirmation(\n  deleteTool,\n  'This will permanently delete your account and all data.'\n);\n```\n\n| Feature | What It Does |\n|---------|-------------|\n| **Rate Limiting** | Sliding window rate limiter per tool |\n| **Input Sanitization** | Strip HTML, control chars, truncate strings/arrays |\n| **Blocked Patterns** | Regex-based input rejection (XSS, injection) |\n| **Audit Logging** | Hook for every invocation with sanitization status |\n| **Confirmation Guards** | `requestUserInteraction()` before destructive actions |\n| **Concurrency Limiting** | Cap parallel tool executions (default: 10) |\n\n---\n\n## Testing\n\n```typescript\nimport {\n  createMockContext,\n  validateToolDefinition,\n  testTool,\n  scoreToolQuality,\n  formatTestResults,\n} from 'webmcp-sdk/testing';\n\n// Validate your tool definition\nconst validation = validateToolDefinition(myTool);\nconsole.log(validation.errors);    // Schema/name issues\nconsole.log(validation.warnings);  // LLM readability tips\n\n// Score tool quality for LLM consumption\nconst { score, maxScore, breakdown } = scoreToolQuality(myTool);\nconsole.log(`Quality: ${score}/${maxScore}`);\n\n// Run test cases\nconst results = await testTool(myTool, [\n  { name: 'basic search', input: { query: 'shoes' }, validate: (r) =\u003e r.results.length \u003e 0 },\n  { name: 'empty query fails', input: {}, expectError: /required/ },\n]);\nconsole.log(formatTestResults(results));\n\n// Mock browser for integration tests\nconst { context, invoke } = createMockContext();\ncontext.registerTool(myTool);\nconst result = await invoke('my-tool', { query: 'test' });\n```\n\n---\n\n## How It Relates to Chrome 146 / W3C WebMCP\n\nChrome's WebMCP is the browser-native standard — the low-level API (`navigator.modelContext`) that lets websites declare callable tools for AI agents. `webmcp-sdk` is the implementation layer: builder pattern, React hooks, Express middleware, security, and testing utilities that make building Chrome WebMCP-compliant sites practical.\n\n```typescript\n// Raw Chrome WebMCP API\nnavigator.modelContext.tools = [{\n  name: 'search',\n  description: 'Search products',\n  inputSchema: { type: 'object', properties: { query: { type: 'string' } } },\n}];\n\n// webmcp-sdk — same result, less code\nserver.tool('search', {\n  description: 'Search products',\n  parameters: z.object({ query: z.string() }),\n  handler: async ({ query }) =\u003e searchProducts(query),\n});\n```\n\nSites built with `webmcp-sdk` will be natively agent-ready when Chrome WebMCP graduates from Canary to stable — no refactoring required.\n\n---\n\n## Browser Support\n\n| Browser | Status | Version |\n|---------|--------|---------|\n| Chrome | ✅ Early Preview (flag-gated) | 146+ |\n| Edge | 🟡 Expected (shares Chromium) | TBD |\n| Firefox | ⏳ No signal yet | — |\n| Safari | ⏳ No signal yet | — |\n\n**Enable in Chrome 146:** `chrome://flags` → \"Experimental Web Platform Features\" → Enable → Relaunch\n\n---\n\n## API Reference\n\n### Core\n\n| Export | Type | Description |\n|--------|------|-------------|\n| `createKit(config?)` | Function | Create a WebMCP Kit instance |\n| `tool(name)` | Function | Start building a tool with fluent API |\n| `defineTool(name, desc, schema, handler)` | Function | Quick tool definition |\n| `WebMCPKit.isAvailable()` | Static | Check if `navigator.modelContext` exists |\n| `kit.register(tool, opts?)` | Method | Register a tool |\n| `kit.unregister(name)` | Method | Remove a tool |\n| `kit.invoke(name, input)` | Method | Call a tool directly (for testing) |\n| `kit.getTools()` | Method | List all registered tools |\n\n### Config Options\n\n```typescript\ncreateKit({\n  prefix: 'myapp',                          // Tool name prefix\n  debug: true,                               // Console logging\n  maxConcurrent: 10,                         // Max parallel handler executions\n  onError: (err, name) =\u003e {},               // Global error handler\n  onBeforeInvoke: (event) =\u003e true,          // Block/allow invocations\n  onAfterInvoke: (event, result) =\u003e {},     // Post-invocation hook\n});\n```\n\n---\n\n## Roadmap\n\n- [x] Core SDK with TypeScript types\n- [x] Builder pattern for tool definitions\n- [x] Input validation (JSON Schema)\n- [x] Security middleware (rate limit, sanitize, block, audit)\n- [x] React hooks\n- [x] Testing utilities + mock context\n- [x] Tool quality scorer\n- [x] Express auto-discovery middleware\n- [ ] Vue/Svelte adapters\n- [ ] CLI scanner (auto-generate tools from existing forms/APIs)\n- [ ] `.well-known/webmcp` manifest generator\n- [ ] Next.js / Remix integration\n- [ ] Declarative HTML annotation parsing\n\n---\n\n## License\n\nMIT\n\n---\n\nBuilt by [up2itnow](https://github.com/up2itnow) · Part of the agentic web infrastructure stack\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fup2itnow0822%2Fwebmcp-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fup2itnow0822%2Fwebmcp-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fup2itnow0822%2Fwebmcp-sdk/lists"}