From 66b26387749385fb35d809d95464f4fdb531fb21 Mon Sep 17 00:00:00 2001 From: Basil Hosmer Date: Tue, 7 Oct 2025 23:49:50 -0400 Subject: [PATCH] more doc tweaks Restructure main README with clear sections, add LICENSE file, and streamline examples README. --- LICENSE | 21 ++ README.md | 521 +++++++++++++++++---------------------------- examples/README.md | 116 +++------- 3 files changed, 242 insertions(+), 416 deletions(-) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ad75c9e --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Anthropic, PBC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 07b4fa9..4ac67fb 100644 --- a/README.md +++ b/README.md @@ -12,16 +12,38 @@ This repository provides a complete implementation of an MCP server that: The [Model Context Protocol](https://modelcontextprotocol.io) is an open standard that enables seamless integration between AI applications and external data sources, tools, and services. -## Why OAuth for MCP? +## Table of Contents -MCP servers often handle sensitive operations and data. This implementation shows how to: -- Authenticate users before granting access to MCP resources -- Integrate with existing identity providers (Auth0, Okta, Google) -- Implement user session isolation in multi-tenant environments -- Scale horizontally while maintaining security +- [Getting Started](#getting-started) + - [Quick Start](#quick-start) + - [Installation](#installation) + - [Testing](#testing) + - [Repository Structure](#repository-structure) +- [Understanding the System](#understanding-the-system) + - [Features](#features) + - [Authentication & Authorization](#authentication--authorization) + - [Configuration](#configuration) + - [Customizing for Your Use Case](#customizing-for-your-use-case) +- [Development & Operations](#development--operations) + - [Development](#development) + - [Common Issues & Solutions](#common-issues--solutions) + - [Technical Details](#technical-details) + - [Monitoring & Debugging](#monitoring--debugging) +- [Reference](#reference) + - [API Reference](#api-reference) + - [Security](#security) + - [External Resources](#external-resources) +- [Contributing](#contributing) + - [License](#license) + +--- + +# Getting Started ## Quick Start +*For detailed installation instructions, see [Installation](#installation) below.* + Get the server running in 5 minutes: ```bash @@ -46,158 +68,110 @@ npx -y @modelcontextprotocol/inspector # (Make sure to include the http:// prefix!) ``` -For detailed instructions, see [Installation](#installation). +## Installation -## Repository Structure +### Prerequisites +- Node.js >= 16 +- npm or yarn +- Docker runtime (for Redis) -This repository demonstrates a production-ready MCP deployment pattern with separate authorization and resource servers: +### Step 1: Install Docker Runtime +Choose one option: +**macOS (Recommended: OrbStack)** +```bash +brew install orbstack +# Start OrbStack daemon (required before using Docker commands) +orbctl start +# Or download from https://orbstack.dev/download ``` -auth-server/ # OAuth 2.0 authorization server (demo only - replace in production) - └── src/ # Authorization endpoints and token management -mcp-server/ # MCP resource server (customize tools/resources/prompts) - └── src/ # MCP protocol implementation with external auth +**Windows/Linux: Docker Desktop** +- Download from https://www.docker.com/products/docker-desktop +- Start Docker Desktop after installation -scripts/ # Testing and deployment scripts -docs/ # Architecture and API documentation -examples/ # Example code and usage patterns +**Alternative: Local Redis Installation** +```bash +# macOS +brew install redis && brew services start redis + +# Ubuntu/Debian +sudo apt-get install redis-server && sudo systemctl start redis ``` -The architecture separates authentication concerns from MCP functionality, allowing you to integrate with commercial OAuth providers (Auth0, Okta, etc.). +### Step 2: Clone and Install Dependencies +```bash +git clone https://github.com/modelcontextprotocol/example-remote-server.git +cd example-remote-server +npm install # Installs dependencies for all workspaces +``` -## Customizing for Your Use Case +### Step 3: Start Redis +```bash +# Ensure Docker/OrbStack is running first! +docker compose up -d -This is a reference implementation with demo tools, resources, and prompts. To adapt it for production: -- **Replace MCP features:** See [Customization Guide](docs/customization-guide.md) for replacing demo functionality with your own -- **Integrate OAuth provider:** See [OAuth Architecture Patterns](docs/oauth-architecture-patterns.md) for production authentication setup +# Verify Redis is running +docker compose ps +``` -## Usage Examples +### Step 4: Start the Servers +```bash +# Start both servers concurrently +npm run dev + +# Or start them individually: +npm run dev:auth-server # Auth server on http://localhost:3001 +npm run dev:mcp-server # MCP server on http://localhost:3232 +``` -### Making Your First MCP Request +## Testing -Once the servers are running, here's how to interact with them: +### With MCP Inspector (Recommended) -#### 1. Register an OAuth Client +The easiest way to test the server: ```bash -# Register your application with the auth server -curl -X POST http://localhost:3001/register \ - -H "Content-Type: application/json" \ - -d '{ - "client_name": "my-mcp-client", - "redirect_uris": ["http://localhost:3000/callback"] - }' - -# Response: -# { -# "client_id": "abc123...", -# "client_secret": "xyz789...", -# "client_name": "my-mcp-client" -# } -``` +# 1. Ensure servers are running (npm run dev) -#### 2. Get an Access Token +# 2. Launch Inspector +npx -y @modelcontextprotocol/inspector -For testing, use the MCP Inspector which handles the OAuth flow automatically. For programmatic access, implement the OAuth 2.0 authorization code flow (see [docs/oauth-flow.md](docs/oauth-flow.md)). +# 3. Connect to http://localhost:3232/mcp +# 4. Complete OAuth flow in the Auth tab +# 5. Test tools, resources, and prompts interactively +``` -#### 3. Initialize MCP Session +### With Example Scripts -```bash -# Initialize a new MCP session -curl -X POST http://localhost:3232/mcp \ - -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "jsonrpc": "2.0", - "id": "1", - "method": "initialize", - "params": { - "protocolVersion": "2024-11-05", - "capabilities": {}, - "clientInfo": { - "name": "my-client", - "version": "1.0" - } - } - }' - -# Response includes session ID for subsequent requests -``` +The `examples/` directory contains runnable code demonstrating OAuth and MCP interactions: -#### 4. Use MCP Features +- **`client.js`**: Complete Node.js example with OAuth flow and MCP operations +- **`curl-examples.sh`**: Shell script showing raw HTTP/curl usage -```bash -# List available tools -curl -X POST http://localhost:3232/mcp \ - -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ - -H "Mcp-Session-Id: YOUR_SESSION_ID" \ - -H "Content-Type: application/json" \ - -d '{ - "jsonrpc": "2.0", - "id": "2", - "method": "tools/list" - }' - -# Call a tool (echo example) -curl -X POST http://localhost:3232/mcp \ - -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ - -H "Mcp-Session-Id: YOUR_SESSION_ID" \ - -H "Content-Type: application/json" \ - -d '{ - "jsonrpc": "2.0", - "id": "3", - "method": "tools/call", - "params": { - "name": "echo", - "arguments": { - "message": "Hello, MCP!" - } - } - }' -``` +See [examples/README.md](examples/README.md) for detailed usage. -For more examples, see the [examples/](examples/) directory. +## Repository Structure -## Understanding the Flow +This repository demonstrates a production-ready MCP deployment pattern with separate authorization and resource servers: -```mermaid -sequenceDiagram - participant User - participant Client as Your App - participant Auth as Auth Server (:3001) - participant MCP as MCP Server (:3232) +``` +auth-server/ # OAuth 2.0 authorization server (demo only - replace in production) + └── src/ # Authorization endpoints and token management - User->>Client: Wants to use MCP - Client->>Auth: 1. Register & OAuth flow - Auth->>User: 2. Login page - User->>Auth: 3. Authenticate - Auth->>Client: 4. Access token - Client->>MCP: 5. MCP request + token - MCP->>Auth: 6. Validate token - Auth->>MCP: 7. Token valid ✓ - MCP->>Client: 8. MCP response - Client->>User: 9. Results +mcp-server/ # MCP resource server (customize tools/resources/prompts) + └── src/ # MCP protocol implementation with external auth + +scripts/ # Testing and deployment scripts +docs/ # Architecture and API documentation +examples/ # Example code and usage patterns ``` -The auth server is separate so you can easily replace it with Auth0, Okta, or any OAuth provider. See [docs/oauth-architecture-patterns.md](docs/oauth-architecture-patterns.md) for integration guidance. +The architecture separates authentication concerns from MCP functionality, allowing you to integrate with commercial OAuth providers (Auth0, Okta, etc.). -## Table of Contents +--- -- [Quick Start](#quick-start) -- [Features](#features) -- [Installation](#installation) -- [Configuration](#configuration) -- [Architecture](#architecture) -- [Development](#development) - - [Testing with MCP Inspector](#testing-with-mcp-inspector) - - [Automated End-to-End Testing](#automated-end-to-end-testing) -- [Common Issues & Solutions](#common-issues--solutions) -- [Technical Details](#technical-details) -- [API Reference](#api-reference) -- [Security](#security) -- [Monitoring & Debugging](#monitoring--debugging) -- [Contributing](#contributing) +# Understanding the System ## Features @@ -225,62 +199,51 @@ The auth server is separate so you can easily replace it with Auth0, Okta, or an - **Security Headers**: CSP, HSTS, X-Frame-Options, and more - **Bearer Token Auth**: Middleware for protected endpoints -## Installation - -### Prerequisites -- Node.js >= 16 -- npm or yarn -- Docker runtime (for Redis) +## Authentication & Authorization -### Step 1: Install Docker Runtime -Choose one option: +Per the [MCP Authorization specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization), this implementation demonstrates a production-ready pattern with separate authorization and resource servers. -**macOS (Recommended: OrbStack)** -```bash -brew install orbstack -# Start OrbStack daemon (required before using Docker commands) -orbctl start -# Or download from https://orbstack.dev/download -``` +### Why OAuth for MCP? -**Windows/Linux: Docker Desktop** -- Download from https://www.docker.com/products/docker-desktop -- Start Docker Desktop after installation +MCP servers often handle sensitive operations and data. This implementation shows how to: +- Authenticate users before granting access to MCP resources +- Integrate with existing identity providers (Auth0, Okta, Google) +- Implement user session isolation in multi-tenant environments +- Scale horizontally while maintaining security -**Alternative: Local Redis Installation** -```bash -# macOS -brew install redis && brew services start redis +### Authentication Flow -# Ubuntu/Debian -sudo apt-get install redis-server && sudo systemctl start redis -``` +```mermaid +sequenceDiagram + participant User + participant Client as Your App + participant Auth as Auth Server (:3001) + participant MCP as MCP Server (:3232) -### Step 2: Clone and Install Dependencies -```bash -git clone https://github.com/modelcontextprotocol/example-remote-server.git -cd example-remote-server -npm install # Installs dependencies for all workspaces + User->>Client: Wants to use MCP + Client->>Auth: 1. Register & OAuth flow + Auth->>User: 2. Login page + User->>Auth: 3. Authenticate + Auth->>Client: 4. Access token + Client->>MCP: 5. MCP request + token + MCP->>Auth: 6. Validate token + Auth->>MCP: 7. Token valid ✓ + MCP->>Client: 8. MCP response + Client->>User: 9. Results ``` -### Step 3: Start Redis -```bash -# Ensure Docker/OrbStack is running first! -docker compose up -d +This architecture pattern: +- **Separates concerns**: Auth server handles OAuth, MCP server handles protocol +- **Enables integration**: Can replace auth server with Auth0, Okta, etc. +- **Scales independently**: Auth and MCP servers can scale based on their load +- **Follows standards**: Uses OAuth 2.0 and token introspection (RFC 7662) -# Verify Redis is running -docker compose ps -``` +### Mock Identity Provider -### Step 4: Start the Servers -```bash -# Start both servers concurrently -npm run dev +The `/mock-upstream-idp` endpoints simulate what a real identity provider (Google, GitHub, corporate SSO) would do. In production, users would be redirected to their actual identity provider for login. This mock implementation helps you test the complete flow locally without external dependencies. -# Or start them individually: -npm run dev:auth-server # Auth server on http://localhost:3001 -npm run dev:mcp-server # MCP server on http://localhost:3232 -``` +For detailed OAuth flow analysis including data storage and TTLs, see [docs/oauth-flow.md](docs/oauth-flow.md). +For alternative patterns like embedded OAuth, see [docs/oauth-architecture-patterns.md](docs/oauth-architecture-patterns.md). ## Configuration @@ -302,82 +265,15 @@ AUTH_SERVER_URL=http://localhost:3001 # External auth server URL REDIS_URL=redis://localhost:6379 # Redis connection ``` -## Architecture - -Per the [MCP Authorization specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization), this implementation demonstrates a production-ready pattern with separate authorization and resource servers. - -### System Architecture - -```mermaid -graph TD - Client["MCP Client
(Inspector)"] - MCP["MCP Server
(port 3232)
Resource Server"] - Auth["Auth Server
(port 3001)
OAuth Server"] - - Client <-->|"1. Discover metadata"| MCP - Client <-->|"2. OAuth flow
(register, authorize, token)"| Auth - Client <-->|"3. Use tokens for MCP resources"| MCP - MCP <-->|"Token validation
(introspect)"| Auth -``` - -This architecture pattern: -- **Separates concerns**: Auth server handles OAuth, MCP server handles protocol -- **Enables integration**: Can replace auth server with Auth0, Okta, etc. -- **Scales independently**: Auth and MCP servers can scale based on their load -- **Follows standards**: Uses OAuth 2.0 and token introspection (RFC 7662) - -For alternative patterns like embedded OAuth, see [docs/oauth-architecture-patterns.md](docs/oauth-architecture-patterns.md). - -### OAuth Flow - -The implementation uses OAuth 2.1 with PKCE. For detailed flow analysis including data storage, TTLs, and implementation details, see [docs/oauth-flow.md](docs/oauth-flow.md). +## Customizing for Your Use Case -### Understanding the Mock Identity Provider +This is a reference implementation with demo tools, resources, and prompts. To adapt it for production: +- **Replace MCP features:** See [Customization Guide](docs/customization-guide.md) for replacing demo functionality with your own +- **Integrate OAuth provider:** See [OAuth Architecture Patterns](docs/oauth-architecture-patterns.md) for production authentication setup -The `/mock-upstream-idp` endpoints simulate what a real identity provider (Google, GitHub, corporate SSO) would do. In production, users would be redirected to their actual identity provider for login. This mock implementation helps you test the complete flow locally without external dependencies. +--- -### Project Structure -``` -├── auth-server/ # OAuth authorization server -│ ├── src/ -│ │ ├── index.ts # Auth server entry point -│ │ ├── auth/ -│ │ │ ├── provider.ts # FeatureReferenceAuthProvider -│ │ │ └── auth-core.ts # Token generation, PKCE -│ │ ├── services/ # Auth services, redis-auth -│ │ ├── handlers/ # Mock upstream auth -│ │ └── utils/logger.ts # Structured logging -│ ├── package.json -│ ├── tsconfig.json -│ └── .env -│ -├── mcp-server/ # MCP resource server -│ ├── src/ -│ │ ├── index.ts # MCP server entry point -│ │ ├── auth/ -│ │ │ ├── external-verifier.ts # Token introspection -│ │ │ └── auth-core.ts -│ │ ├── services/ # MCP server, redisTransport -│ │ ├── handlers/ # SHTTP, SSE handlers -│ │ └── utils/logger.ts -│ ├── package.json -│ ├── tsconfig.json -│ └── .env -│ -├── scripts/ # Testing and deployment -│ └── test-e2e.sh # End-to-end OAuth + MCP verification -├── docs/ -│ ├── customization-guide.md # How to adapt this for your use case -│ ├── endpoints.md # API endpoint reference -│ ├── oauth-flow.md # OAuth flow documentation -│ ├── oauth-architecture-patterns.md # OAuth integration guidance -│ └── session-ownership.md # Session management details -├── examples/ # Example code and usage patterns -│ ├── client.js # Node.js client example -│ └── curl-examples.sh # Shell script with curl examples -├── package.json # Root workspace configuration -└── docker-compose.yml # Redis service -``` +# Development & Operations ## Development @@ -404,28 +300,6 @@ npm run typecheck # Typecheck all code npm run test:e2e # End-to-end test ``` -### Testing with MCP Inspector - -The MCP Inspector is a web-based tool for testing MCP servers. - -#### Prerequisites -1. Ensure Docker/OrbStack is running -2. Ensure Redis is running: `docker compose ps` - -#### Test the Server -```bash -# 1. Start both servers (Redis must already be running) -npm run dev - -# 2. Launch MCP Inspector in a new terminal -npx -y @modelcontextprotocol/inspector - -# 3. Connect to: http://localhost:3232/mcp -# 4. Auth flow will redirect to :3001 for authentication -# 5. Complete OAuth flow in the Auth tab -# 6. Test MCP features (tools, resources, prompts, etc.) -``` - ### Automated End-to-End Testing The E2E script in `scripts/test-e2e.sh` verifies the complete OAuth flow and all MCP features: @@ -482,14 +356,6 @@ The script: - Check for existing processes: `lsof -i :3232` or `lsof -i :3001` - Kill existing processes or change PORT in .env files -### Understanding the Mock IDP -- The mock IDP simulates user login for testing -- In production, this would be replaced by: - - Your company's SSO system (LDAP, Active Directory) - - Auth0/Okta login page - - Google/GitHub OAuth -- The mock IDP creates random user IDs for testing multi-user scenarios - ### "Authentication service unavailable" (HTTP 503) - **Cause**: Auth server is not running or not reachable - **What happens**: MCP server runs in degraded mode @@ -564,34 +430,6 @@ Backwards-compatible [transport](https://modelcontextprotocol.io/specification/2 - Redis-backed message routing - Real-time event delivery -## API Reference - -For a complete listing of all endpoints provided by each server, including OAuth authorization endpoints, MCP resource endpoints, and demo identity provider endpoints, see [docs/endpoints.md](docs/endpoints.md). - -## Security - -### Implemented Security Measures -- **Authentication**: [OAuth 2.0](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization) with bearer tokens -- **Token Validation**: Introspection via [RFC 7662](https://datatracker.ietf.org/doc/html/rfc7662) -- **Authorization**: User-based session ownership -- **Session Isolation**: Users can only access their own sessions -- **Security Headers**: - - Content Security Policy (CSP) - - Strict Transport Security (HSTS) - - X-Frame-Options - - X-Content-Type-Options -- **Input Validation**: Zod schemas for all inputs -- **Error Handling**: Sanitized error responses - -### Security Best Practices -1. Always use HTTPS in production -2. Configure proper CORS origins -3. Use strong client secrets -4. Enable all security headers -5. Monitor session lifetimes -6. Implement rate limiting -7. Use structured logging - ## Monitoring & Debugging ### Logging @@ -624,34 +462,39 @@ redis-cli GET "session:{sessionId}:owner" - Source maps for debugging - Redis monitoring commands -## Contributing +--- -We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for details. +# Reference -### Development Workflow -1. Fork the repository -2. Create a feature branch -3. Implement your changes -4. Add tests for new functionality -5. Ensure all tests pass -6. Run linting and fix issues -7. Submit a pull request - -### Code Style -- TypeScript with strict mode -- ESLint configuration included -- Prettier formatting recommended -- Comprehensive type definitions +## API Reference -## License +For a complete listing of all endpoints provided by each server, including OAuth authorization endpoints, MCP resource endpoints, and demo identity provider endpoints, see [docs/endpoints.md](docs/endpoints.md). -This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. +## Security -## Acknowledgments +### Implemented Security Measures +- **Authentication**: [OAuth 2.0](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization) with bearer tokens +- **Token Validation**: Introspection via [RFC 7662](https://datatracker.ietf.org/doc/html/rfc7662) +- **Authorization**: User-based session ownership +- **Session Isolation**: Users can only access their own sessions +- **Security Headers**: + - Content Security Policy (CSP) + - Strict Transport Security (HSTS) + - X-Frame-Options + - X-Content-Type-Options +- **Input Validation**: Zod schemas for all inputs +- **Error Handling**: Sanitized error responses -Built by the Model Context Protocol team as a reference implementation for the MCP ecosystem. +### Security Best Practices +1. Always use HTTPS in production +2. Configure proper CORS origins +3. Use strong client secrets +4. Enable all security headers +5. Monitor session lifetimes +6. Implement rate limiting +7. Use structured logging -## References +## External Resources ### MCP Documentation - [Model Context Protocol Documentation](https://modelcontextprotocol.io) @@ -672,8 +515,26 @@ Built by the Model Context Protocol team as a reference implementation for the M - [OAuth.net: End User Authentication](https://oauth.net/articles/authentication/) - [The Resource Server - OAuth 2.0 Simplified](https://www.oauth.com/oauth2-servers/the-resource-server/) -### Architecture Patterns -This implementation demonstrates patterns discussed in: -- [Stack Overflow: Separating Resource and Authorization Servers](https://stackoverflow.com/questions/16228193/oauth-2-separating-resource-server-and-authorization-server) -- [OAuth 2.0 Overview - Curity](https://curity.io/resources/learn/oauth-overview/) -- Microsoft identity platform documentation on [OAuth 2.0 flows](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow) \ No newline at end of file +--- + +# Contributing + +We welcome contributions! + +### Development Workflow +1. Fork the repository +2. Create a feature branch +3. Implement your changes +4. Add tests for new functionality +5. Ensure all tests pass +6. Run linting and fix issues +7. Submit a pull request + +### Code Style +- TypeScript with strict mode +- ESLint configuration included +- Comprehensive type definitions + +## License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. \ No newline at end of file diff --git a/examples/README.md b/examples/README.md index 76c9280..c8246ca 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,6 +1,12 @@ # MCP Server Examples -This directory contains example code demonstrating how to interact with the MCP server. +These examples demonstrate interaction with the MCP server, covering OAuth authentication, session management, and MCP operations (tools, resources, prompts). + +**Authentication is the most complex part** of using an MCP server with OAuth. The examples demonstrate authentication interactions using two different step-by-step approaches: +- **client.js**: runs the server's end-to-end auth flow in the browser +- **curl-examples.sh**: uses raw HTTP interactions (requires obtaining an access token separately) + +See below for details. ## Prerequisites @@ -13,39 +19,6 @@ Before running any examples, ensure: ## Available Examples -### curl-examples.sh - -Shell script demonstrating API interactions using curl. - -**Features:** -- OAuth client registration -- MCP session initialization -- Tool calls (echo, add) -- Resource listing and reading -- Prompt operations - -**Three-step workflow:** -```bash -# Make executable -chmod +x curl-examples.sh - -# Step 1: Setup - Register OAuth client and get instructions -./curl-examples.sh - -# Step 2: Create session - Get an access token (via Inspector or client.js), then: -./curl-examples.sh YOUR_ACCESS_TOKEN -# → Initializes MCP session and displays session ID - -# Step 3: Run examples - Use both access token and session ID: -./curl-examples.sh YOUR_ACCESS_TOKEN YOUR_SESSION_ID -# → Demonstrates all MCP features (tools, resources, prompts) -``` - -**Quick reference:** -- Run `./curl-examples.sh --help` for detailed usage -- Get access token from MCP Inspector or `node client.js` -- Each step explains what to do next - ### client.js Node.js client showing programmatic interaction with the MCP server. @@ -68,67 +41,38 @@ chmod +x client.js **Note:** When you complete the OAuth flow in your browser, you'll be redirected to `http://localhost:8080/callback` which will show "site can't be reached". This is expected! Simply copy the authorization code from the URL in your browser's address bar (the long string after `code=`). The script will exchange this for an access token and display it for use with other tools. -## Understanding OAuth Tokens - -**Authorization Code** vs **Access Token**: -- **Authorization Code**: The temporary code you get from the browser redirect (e.g., `302a80e8...`) - - One-time use only - - Must be exchanged for an access token - - Expires quickly (usually within minutes) -- **Access Token**: The actual bearer token for API authentication (e.g., `mcp_at_...`) - - Used in the `Authorization: Bearer` header - - Valid for 7 days - - What you need for `curl-examples.sh` +### curl-examples.sh -## Getting an Access Token +Shell script demonstrating API interactions using curl. -### Option 1: MCP Inspector (Easiest) +**Features:** +- OAuth client registration +- MCP session initialization +- Tool calls (echo, add) +- Resource listing and reading +- Prompt operations +**Three-step workflow:** ```bash -# Launch inspector -npx -y @modelcontextprotocol/inspector - -# Connect to http://localhost:3232/mcp -# Complete OAuth flow in the Auth tab -# Copy the access token from the debug console -``` - -### Option 2: Manual OAuth Flow - -1. Register a client (see examples) -2. Navigate to authorization URL -3. Complete authentication -4. Exchange authorization code for token -5. Use token in API calls - -## Common Patterns - -### Making MCP Requests - -All MCP requests follow this pattern: +# Make executable +chmod +x curl-examples.sh -```javascript -{ - "jsonrpc": "2.0", - "id": "unique-id", - "method": "category/action", - "params": { /* method-specific parameters */ } -} -``` +# Step 1: Setup - Register OAuth client and get instructions +./curl-examples.sh -### Required Headers +# Step 2: Create session - Get an access token (via Inspector or client.js), then: +./curl-examples.sh YOUR_ACCESS_TOKEN +# → Initializes MCP session and displays session ID -``` -Authorization: Bearer YOUR_ACCESS_TOKEN -Content-Type: application/json -Mcp-Session-Id: YOUR_SESSION_ID // After initialization +# Step 3: Run examples - Use both access token and session ID: +./curl-examples.sh YOUR_ACCESS_TOKEN YOUR_SESSION_ID +# → Demonstrates all MCP features (tools, resources, prompts) ``` -### Session Lifecycle - -1. **Initialize**: Create a new session -2. **Use**: Make requests with session ID -3. **Terminate**: Optional cleanup (auto-expires after 5 min) +**Quick reference:** +- Run `./curl-examples.sh --help` for detailed usage +- Requires an access token (get from MCP Inspector or `node client.js`) +- Each step explains what to do next ## Troubleshooting