{"id":30202813,"url":"https://github.com/workos/vercel-mcp-example","last_synced_at":"2025-08-13T11:08:00.254Z","repository":{"id":305779695,"uuid":"1012703535","full_name":"workos/vercel-mcp-example","owner":"workos","description":null,"archived":false,"fork":false,"pushed_at":"2025-08-04T06:19:01.000Z","size":1560,"stargazers_count":3,"open_issues_count":13,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-08-08T12:01:39.304Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://vercel-mcp-example.vercel.app","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/workos.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-02T18:41:47.000Z","updated_at":"2025-08-03T03:36:11.000Z","dependencies_parsed_at":"2025-07-22T01:44:28.370Z","dependency_job_id":"7816a664-27c6-45a2-ab7b-8d0a70badcdf","html_url":"https://github.com/workos/vercel-mcp-example","commit_stats":null,"previous_names":["workos/vercel-mcp-example"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/workos/vercel-mcp-example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/workos%2Fvercel-mcp-example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/workos%2Fvercel-mcp-example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/workos%2Fvercel-mcp-example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/workos%2Fvercel-mcp-example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/workos","download_url":"https://codeload.github.com/workos/vercel-mcp-example/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/workos%2Fvercel-mcp-example/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270228408,"owners_count":24548821,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-13T02:00:09.904Z","response_time":66,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":[],"created_at":"2025-08-13T11:07:57.905Z","updated_at":"2025-08-13T11:08:00.146Z","avatar_url":"https://github.com/workos.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# MCP Authentication Demo: Vercel MCP Adapter + WorkOS AuthKit\n\nA production-ready template for building authenticated MCP servers using the Vercel MCP adapter and WorkOS AuthKit. Clone this repo, add your tools, and deploy instantly to Vercel with enterprise authentication built-in.\n\n## What This Demo Shows\n\n**Core insight**: Individual tools decide if they need authentication. No global auth requirements, no complex middleware.\n\n### The Pattern\n\n```typescript\n// Without auth: pure business logic\nserver.tool(\"publicData\", {}, async () =\u003e {\n  return getPublicData();\n});\n\n// With auth: same logic + one helper call\nserver.tool(\"userData\", {}, async (args, extra) =\u003e {\n  const user = ensureUserAuthenticated(extra.authInfo); // ← Just add this line\n  return getUserData(user);\n});\n```\n\n### How It Works\n\n1. **Wrap your handler** with `experimental_withMcpAuth`:\n```typescript\nconst authHandler = experimental_withMcpAuth(handler, verifyToken, { \n  required: false // ← Tools decide individually\n});\n```\n\n2. **Verify tokens** with direct WorkOS calls:\n```typescript\nconst verifyToken = async (req: Request, bearerToken?: string) =\u003e {\n  if (!bearerToken) return undefined; // Allow unauthenticated requests\n  \n  const { payload } = await jwtVerify(bearerToken, JWKS);        // WorkOS JWT\n  const user = await workos.userManagement.getUser(payload.sub); // WorkOS User API\n  \n  return { token: bearerToken, clientId: user.id, extra: { user } };\n};\n```\n\n3. **Tools get user context** through our helper:\n```typescript\n// lib/auth/helpers.ts\nexport const ensureUserAuthenticated = (authInfo: AuthInfo | undefined): User =\u003e {\n  if (!authInfo?.extra?.user) {\n    throw new Error('Authentication required for this tool');\n  }\n  return authInfo.extra.user; // WorkOS user object\n};\n```\n\nThat's it! Your MCP server now has enterprise authentication with zero global auth logic.\n\n\u003cdetails\u003e\n\u003csummary\u003eSee the complete implementation\u003c/summary\u003e\n\n```typescript\n// app/mcp/route.ts - Complete authenticated MCP server\nimport { createMcpHandler, experimental_withMcpAuth } from \"@vercel/mcp-adapter\";\nimport { jwtVerify } from \"jose\";\nimport { ensureUserAuthenticated, isAuthenticated } from \"../../lib/auth/helpers\";\n\n// Clean MCP handler - tools decide auth individually\nconst handler = createMcpHandler((server) =\u003e {\n  // Public tool\n  server.tool(\"ping\", {}, async (args, extra) =\u003e {\n    const authenticated = isAuthenticated(extra.authInfo);\n    return { \n      content: [{ \n        type: \"text\", \n        text: authenticated ? \"Hello authenticated user!\" : \"Hello world!\" \n      }] \n    };\n  });\n  \n  // Private tool - decides it needs auth\n  server.tool(\"getUserProfile\", {}, async (args, extra) =\u003e {\n    const user = ensureUserAuthenticated(extra.authInfo); // Throws if not authenticated\n    return { \n      content: [{ \n        type: \"text\", \n        text: `Profile: ${user.email} (${user.firstName} ${user.lastName})` \n      }] \n    };\n  });\n});\n\n// WorkOS token verification\nconst verifyToken = async (req: Request, bearerToken?: string) =\u003e {\n  if (!bearerToken) return undefined;\n  \n  try {\n    const { payload } = await jwtVerify(bearerToken, JWKS);\n    const user = await workos.userManagement.getUser(payload.sub);\n    return { token: bearerToken, clientId: user.id, extra: { user, claims: payload } };\n  } catch (error) {\n    return undefined;\n  }\n};\n\n// Authenticated handler\nconst authHandler = experimental_withMcpAuth(handler, verifyToken, { required: false });\n\nexport { authHandler as GET, authHandler as POST };\n```\n\n\u003c/details\u003e\n\n**Result**: Enterprise authentication with SSO support, automatic user context in tools, and zero-config Vercel deployment.\n\n## Ready-to-Deploy Template\n\nThis isn't just a demo—it's a complete template you can build on:\n\n- **Replace the example tools** in `lib/business/examples.ts` with your own business logic\n- **Add new authenticated tools** using the same pattern shown above\n- **Test everything locally** with the built-in web interface and testing tools\n- **Deploy to Vercel** in one command with enterprise auth already configured\n\n### Built-in Testing Interface\n\nThe template includes a complete testing interface so you can verify your tools work correctly:\n\n![In-app testing interface](public/in-app-testing.webp)\n\nTest both public and authenticated tools directly from your browser, with automatic token management and clear response formatting.\n\n## Quick Start\n\n### 1. Clone and Install\n```bash\ngit clone https://github.com/workos/vercel-mcp-example.git\ncd vercel-mcp-example\npnpm install\n```\n\n\u003e **Note**: We recommend using `pnpm` as it handles React 19 peer dependency warnings gracefully. If using npm, add the `--legacy-peer-deps` flag.\n\n### 2. Set Up WorkOS\n1. Create a [WorkOS account](https://dashboard.workos.com) (free)\n2. Create a new project  \n3. Get your API Key and Client ID from the dashboard\n4. Add `http://localhost:3000/callback` as a redirect URI in AuthKit settings\n\n### 3. Configure Environment\n```bash\ncp .env.example .env.local\n```\n\nFill in your WorkOS credentials:\n```env\nWORKOS_API_KEY=sk_test_your_api_key_here\nWORKOS_CLIENT_ID=client_your_client_id_here\nWORKOS_COOKIE_PASSWORD=your_32_character_secure_random_string\nWORKOS_REDIRECT_URI=http://localhost:3000/callback\n```\n\n### 4. Start the Demo\n```bash\nnpm run dev\n```\n\nVisit [http://localhost:3000](http://localhost:3000) to try the authenticated MCP server!\n\n## Testing the Demo\n\nThe template includes a complete web interface for testing your MCP tools:\n\n1. **Test public tools** - Try `ping` without authentication\n2. **Login with WorkOS** - Use the login button to authenticate  \n3. **Test authenticated tools** - Try tools like `getUserProfile` that require user context\n\nThe interface handles token management automatically and displays responses in a clean, readable format. You can also test with any MCP client by configuring it to use your local server.\n\n## Architecture\n\n```mermaid\ngraph LR\n  A[MCP Client] --\u003e B[authHandler Wrapper]\n  B --\u003e C[JWT Verification]\n  C --\u003e D[MCP Server Tools]\n  B --\u003e E[WorkOS API]\n  \n  style B fill:#ec4899,stroke:#db2777,stroke-width:2px,color:#ffffff\n  style D fill:#f59e0b,stroke:#d97706,stroke-width:2px,color:#ffffff\n```\n\nSimple flow: Client → Auth wrapper → JWT verification → Tools decide if they need user context → WorkOS API (if needed).\n\n## Code Organization\n\nThis template follows a recommended structure for scalable MCP servers:\n\n```\nlib/\n├── auth/\n│   ├── helpers.ts        # ensureUserAuthenticated, isAuthenticated\n│   └── types.ts          # User, WorkOSAuthInfo types\n├── business/\n│   ├── examples.ts       # Example business logic (replace with yours)\n│   └── database.ts       # Database connection/queries\n├── mcp/\n│   ├── tools/\n│   │   ├── public.ts     # Public tools (ping, status)\n│   │   └── examples.ts   # Example authenticated tools\n│   └── server.ts         # Main MCP server setup\n└── utils/\n    ├── validation.ts     # Zod schemas\n    └── errors.ts         # Custom error classes\n```\n\n### Key Files\n\n- **`app/mcp/route.ts`** - The main MCP server with authentication\n- **`lib/auth/helpers.ts`** - Authentication helper functions\n- **`lib/business/examples.ts`** - Example business logic (replace with yours)\n- **`lib/mcp/tools/`** - MCP tool definitions organized by category\n- **`app/components/TestingSection.tsx`** - Built-in testing interface\n- **`lib/with-authkit.ts`** - WorkOS AuthKit setup\n\n## Next Steps\n\n1. **Explore the code** - See how the authentication pattern works\n2. **Build your tools** - Replace `lib/business/examples.ts` with your business logic  \n3. **Test locally** - Use the built-in testing interface to verify everything works\n4. **Deploy to production** - Run `vercel deploy` with your environment variables\n5. **Add advanced features** - Role-based access, organization filtering, etc.\n\n## Why This Stack?\n\n- **Vercel MCP adapter**: Type-safe MCP development with zero-config deployment\n- **WorkOS AuthKit**: Enterprise authentication (SSO, user management, compliance)\n- **Simple Pattern**: Business logic stays clean, security is declarative\n\nPerfect for building production AI tools that need real user authentication and enterprise features.\n\n## Contributing\n\nWe welcome contributions to this project! Here's how you can help:\n\n### Development Setup\n\n1. Fork the repository\n2. Clone your fork: `git clone https://github.com/YOUR_USERNAME/vercel-mcp-example.git`\n3. Install dependencies: `pnpm install` (or `npm install --legacy-peer-deps`)\n4. Create a branch: `git checkout -b feature/your-feature-name`\n5. Make your changes and write tests\n6. Run the test suite: `pnpm run test`\n7. Run linting and formatting: `pnpm run lint \u0026\u0026 pnpm run prettier`\n8. Push to your fork and submit a pull request\n\n### Guidelines\n\n- Write clear, concise commit messages\n- Add tests for new functionality\n- Ensure all tests pass before submitting\n- Follow the existing code style and conventions\n- Update documentation as needed\n\n### Reporting Issues\n\nPlease use the [GitHub Issues](https://github.com/workos/vercel-mcp-example/issues) page to report bugs or request features.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n---\n\n**Questions?** Check the [WorkOS MCP docs](https://workos.com/docs/user-management/mcp) or [Vercel MCP adapter docs](https://sdk.vercel.ai/docs/foundations/mcp).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fworkos%2Fvercel-mcp-example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fworkos%2Fvercel-mcp-example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fworkos%2Fvercel-mcp-example/lists"}