### MCP Client Tool Testing Commands Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/handlers/tools/EXAMPLE_TOOLS_GUIDE.md Provides command-line examples for interacting with MCP tools using `mcp-client`, including listing available tools and calling specific example tools with their respective arguments for testing purposes. ```bash # List all tools including examples mcp-client list-tools # Call elicitation example mcp-client call-tool elicitation_example '{"elicitationType": "preferences"}' # Call sampling example mcp-client call-tool sampling_example '{"taskType": "analyze", "content": "Sample text"}' # Call structured data example mcp-client call-tool structured_data_example '{"dataType": "analytics", "includeNested": true}' ``` -------------------------------- ### Sampling Example Tool Usage Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/handlers/tools/EXAMPLE_TOOLS_GUIDE.md Illustrates how to invoke the `sampling_example` tool, specifying a task type like 'summarize' and the content to be processed by an LLM, showcasing the AI-assisted sampling pattern. ```JSON { "tool": "sampling_example", "arguments": { "taskType": "summarize", "content": "Long article text here..." } } ``` -------------------------------- ### Elicitation Example Tool Usage Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/handlers/tools/EXAMPLE_TOOLS_GUIDE.md Demonstrates how to call the `elicitation_example` tool with specific arguments to request user profile information or custom messages, illustrating the elicitation pattern. ```JSON { "tool": "elicitation_example", "arguments": { "elicitationType": "user_profile", "customMessage": "We need your profile info to personalize the experience" } } ``` -------------------------------- ### Structured Data Example Tool Usage Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/handlers/tools/EXAMPLE_TOOLS_GUIDE.md Shows how to call the `structured_data_example` tool to retrieve structured data, such as user profiles or analytics, with an option to include nested information, demonstrating the structured data pattern. ```JSON { "tool": "structured_data_example", "arguments": { "dataType": "user", "includeNested": true } } ``` -------------------------------- ### Install systemprompt-mcp-server via npm, npx, or Git Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md This snippet provides various methods for installing or setting up the `systemprompt-mcp-server`. Users can install globally via npm, run directly with npx without installation, or clone the repository for development purposes. ```bash # Via npm npm install -g @systemprompt/systemprompt-mcp-server # Via npx (no installation) npx @systemprompt/systemprompt-mcp-server # Clone for development git clone https://github.com/systempromptio/systemprompt-mcp-server.git cd systemprompt-mcp-server npm install npm run build ``` -------------------------------- ### Run All E2E Tests Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/e2e-test/README.md These commands guide you through preparing and executing the entire E2E test suite. First, navigate to the test directory, then install all necessary Node.js dependencies, and finally run all defined tests. ```bash cd e2e-test npm install npm test ``` -------------------------------- ### Implemented MCP Tools Reference Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/CODE_STRUCTURE_GUIDE.md Documents the currently implemented tools within the MCP server, categorized by their domain (Reddit, Example) and providing a brief description of each tool's functionality. ```APIDOC Current Tool Implementations: Reddit Tools: - `get_channel`: Retrieve subreddit posts with sorting options - `get_post`: Fetch specific Reddit post with comments - `get_comment`: Retrieve comment with optional thread context - `get_notifications`: Fetch user notifications and messages - `search_reddit`: Search Reddit with filters and pagination Example Tools (for learning/demonstration): - `elicitation_example`: Demonstrates user input gathering - `sampling_example`: Shows AI-assisted content generation - `structured_data_example`: Demonstrates data formatting - `validation_example`: Shows input validation with Zod - `mcp_logging`: Utility for server-side logging ``` -------------------------------- ### Start MCP Server and Inspector for OAuth Testing Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Provides a two-step process to start the MCP server and then the MCP Inspector in separate terminals. This setup is crucial for initiating and completing the OAuth authentication flow required for testing Reddit interactions. ```bash # Build and start the server npm run build node build/index.js # In another terminal, open the MCP Inspector npx @modelcontextprotocol/inspector build/index.js ``` -------------------------------- ### Guide for Adding New Features Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/CODE_STRUCTURE_GUIDE.md Provides structured steps for extending the server by adding new MCP tools, services, or sampling prompts, detailing file locations and integration points. ```APIDOC Adding New Features: To add a new MCP tool: 1. Create tool constant in `constants/tool/your-tool.ts` 2. Implement handler in `handlers/tools/your-tool.ts` 3. Add Zod schema to `handlers/tool-handlers.ts` 4. Register in tool arrays in `constants/tools.ts` 5. Export from `handlers/tools/index.ts` 6. Add types to `types/` if needed To add a new service: 1. Create service in `services/your-service/` 2. Use dependency injection for auth context 3. Handle errors with custom error types 4. Add appropriate logging with the logger utility 5. Create proper TypeScript interfaces in `types/` To add a new sampling prompt: 1. Create prompt in `constants/sampling/your-prompt.ts` 2. Implement callback in `handlers/callbacks/your-callback.ts` 3. Register callback in the sampling handler 4. Export from appropriate index files ``` -------------------------------- ### Example .env File for Reddit Credentials Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Illustrates the required environment variables for Reddit OAuth application credentials that should be placed in a `.env` file in the project root. These are crucial for the server to authenticate with Reddit. ```bash # Required - Reddit OAuth Application Credentials REDDIT_CLIENT_ID=your_reddit_client_id REDDIT_CLIENT_SECRET=your_reddit_client_secret ``` -------------------------------- ### Client Call for Elicitation Tool Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Demonstrates how a client calls the `elicitation_example` tool to gather dynamic user input. The example highlights different elicitation types supported, such as text input, yes/no confirmation, and multiple-choice selection. ```typescript // Call the elicitation example tool await client.callTool("elicitation_example", { type: "input", prompt: "Enter post title", options: [] }); // The tool demonstrates different elicitation types: // - "input": Text input from user // - "confirm": Yes/no confirmation // - "choice": Multiple choice selection ``` -------------------------------- ### Example Tool Handler: Search Reddit Posts Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/handlers/README.md This TypeScript function demonstrates a complete tool handler for searching Reddit. It showcases argument validation, interaction with a `RedditService`, execution of a search query, and comprehensive notification handling for both success and failure scenarios, returning a formatted MCP response. This example illustrates the typical structure and flow for implementing new tools. ```typescript export async function handleRedditSearch( args: SearchRedditArgs, context: MCPToolContext ): Promise { try { // Validate arguments validateSearchArgs(args); // Get Reddit service with auth const reddit = new RedditService(context.authInfo); // Execute search const results = await reddit.search({ query: args.query, subreddit: args.subreddit, sort: args.sort, limit: args.limit }); // Send success notification await sendOperationNotification( 'search_reddit', `Found ${results.length} results`, context.sessionId ); // Return formatted response return { content: [{ type: 'text', text: JSON.stringify(results, null, 2) }] }; } catch (error) { // Send error notification await sendOperationNotification( 'search_reddit', `Search failed: ${error.message}`, context.sessionId ); throw error; } } ``` -------------------------------- ### Execute Reddit MCP Server E2E Test Suite Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/e2e-test/AUTHENTICATION.md Provides the command-line steps to run the end-to-end test suite for the Reddit MCP Server. This involves navigating to the test directory, installing necessary Node.js dependencies, and then executing the tests using `npm test`. A valid MCP access token is required as a prerequisite. ```bash cd e2e-test npm install npm test ``` -------------------------------- ### Common Development Commands for MCP Server Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Provides a list of essential `npm` commands for managing the project during development. These commands cover dependency installation, TypeScript compilation, watch mode for continuous development, and various testing functionalities. ```bash # Install dependencies npm install # Build TypeScript npm run build # Watch mode for development npm run watch # Run tests (requires OAuth tokens - see below) npm run test # Run end-to-end tests npm run e2e # Build and run with Docker npm run docker ``` -------------------------------- ### Launch MCP Inspector with Built Server Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Command to build the TypeScript project and then launch the MCP Inspector, connecting it to the local server for comprehensive testing. This automates the setup for interactive testing of MCP features. ```bash # Build the server first npm run build # Launch the inspector with the built server npx @modelcontextprotocol/inspector build/index.js ``` -------------------------------- ### Run systemprompt-mcp-server with Docker Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md This Docker command runs the `systemprompt-mcp-server` by pulling the official image, mapping port 3000, and loading environment variables from the `.env` file. It's the simplest way to get the server running without local dependencies. ```bash docker run -it --rm \ -p 3000:3000 \ --env-file .env \ --name mcp-reddit \ node:20-slim \ npx @systemprompt/systemprompt-mcp-server ``` -------------------------------- ### Validation Tool Input Parameters Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Defines example input parameters for the `validation_example` tool, showcasing basic input validation for different data types like strings, numbers, and enums. This tool is implemented in `src/handlers/tools/validation-example.ts`. ```typescript { "test_string": "example", "test_number": 42, "test_enum": "option1" } ``` -------------------------------- ### Start MCP Server with Docker Compose Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/e2e-test/README.md This command initiates the Reddit MCP server using Docker Compose. The '-d' flag runs the containers in detached mode, allowing them to operate in the background. ```bash docker-compose up -d ``` -------------------------------- ### Sampling Definitions API Reference Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/constants/README.md This section outlines the structure and purpose of sampling definition files, which contain prompts and schemas for AI-assisted operations. It serves as a reference for understanding how AI responses are guided and validated for various content generation tasks. ```APIDOC Sampling Definitions (/sampling): Description: Prompts and schemas for AI-assisted operations. Files: create-post.ts: Post generation prompts and schema. create-comment.ts: Comment generation guidance. create-message.ts: Message composition prompts. suggest-action.ts: Action suggestion prompts. index.ts: Exports all sampling messages. ``` -------------------------------- ### Production Environment Variables Configuration Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/SECURITY.md This snippet provides examples of essential environment variables required for a production deployment, including Reddit API credentials, a JWT secret, and OAuth URLs. It emphasizes the need for strong, unique values and suggests a method for generating a secure JWT secret. ```bash # Strong, unique values required REDDIT_CLIENT_ID= REDDIT_CLIENT_SECRET= JWT_SECRET= # Production URLs OAUTH_ISSUER=https://your-domain.com REDIRECT_URL=https://your-domain.com/oauth/reddit/callback ``` -------------------------------- ### TypeScript Logging with `logger` Utility Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/utils/README.md Demonstrates how to use the centralized `logger` utility for structured logging within the application. It provides examples for logging informational messages with contextual data and capturing error messages, including their stack traces, for effective debugging. ```typescript logger.info('Operation started', { operation: 'search', params: { query: 'test' } }); logger.error('Operation failed', { error: error.message, stack: error.stack }); ``` -------------------------------- ### TypeScript Data Transformation Examples Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/utils/README.md Shows how data transformation utilities are utilized to process and standardize data, particularly for external API responses. This includes converting raw API data into internal application types and formatting content for consistent display across different parts of the system. ```typescript // Transform Reddit post const post = transformRedditPost(apiResponse); // Format for display const formatted = formatRedditContent(post); ``` -------------------------------- ### Zod Schema for Structured Data Validation Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Illustrates the use of Zod for defining and validating schemas for tool inputs. This ensures data integrity and automatically provides detailed error messages, as shown with an example schema for Reddit search parameters. ```typescript // Example Zod schema for Reddit search const SearchRedditSchema = z.object({ query: z.string().min(1).max(500).describe("Search query"), subreddit: z.string().optional().describe("Optional subreddit filter"), sort: z.enum(["relevance", "hot", "new", "top"]).default("relevance"), time: z.enum(["hour", "day", "week", "month", "year", "all"]).default("all"), limit: z.number().int().min(1).max(100).default(25) }); // Validation is automatic and provides detailed error messages const args = SearchRedditSchema.parse(request.params.arguments); ``` -------------------------------- ### Define Handler Context Types in TypeScript Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/types/README.md Example of defining an interface for handler contexts, encapsulating essential information like session ID and authentication details. This ensures that handlers receive a consistent and type-safe context object. ```typescript interface MCPToolContext { sessionId: string; authInfo: RedditAuthInfo; } ``` -------------------------------- ### Configure Reddit MCP Server Environment Variables Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/e2e-test/AUTHENTICATION.md Defines the essential environment variables for the Reddit MCP Server. This includes the Reddit application client ID and secret for OAuth, and a secure secret for signing and verifying JWT tokens. These variables are crucial for server operation and authentication. ```env REDDIT_CLIENT_ID=your_reddit_app_id REDDIT_CLIENT_SECRET=your_reddit_app_secret JWT_SECRET=your-secure-random-string ``` -------------------------------- ### Configure MCP Access Token for E2E Tests Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/e2e-test/AUTHENTICATION.md Specifies the environment variable used to provide the MCP access token for end-to-end tests. This token, obtained through the OAuth flow, authenticates test requests against the MCP server. It must be saved in the `e2e-test/.env` file before test execution. ```env MCP_ACCESS_TOKEN=your-mcp-jwt-token ``` -------------------------------- ### MCP OAuth 2.1 Initial 401 Response Header Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md This code snippet shows the `WWW-Authenticate` header sent by the server in response to an unauthenticated request. It specifies the Bearer authentication scheme and the realm for the MCP Reddit Server, guiding clients on how to proceed with authentication. ```typescript WWW-Authenticate: Bearer realm="MCP Reddit Server" ``` -------------------------------- ### TypeScript Type Guard for URL Validation Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/utils/README.md Provides an example of a TypeScript type guard function, `isValidUrl`, which performs runtime type checking. This utility determines if an unknown value is a valid string representing a URL, narrowing its type to `string` if the validation is successful. ```typescript export function isValidUrl(value: unknown): value is string { if (typeof value !== 'string') return false; try { new URL(value); return true; } catch { return false; } } ``` -------------------------------- ### Create Mock Data with Type Safety in TypeScript Tests Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/types/README.md Example of creating mock data for testing purposes, leveraging TypeScript's type inference and compile-time checks. This ensures that test data adheres to defined interfaces, preventing common errors and improving test reliability. ```typescript const mockPost: RedditPost = { id: 'test123', title: 'Test Post', // TypeScript ensures all required fields }; ``` -------------------------------- ### TypeScript Input Validation Functions Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/utils/README.md Illustrates various input validation functions available for common data types and scenarios. Examples include validating required string fields, optional numeric values within a specified range, and ensuring a value matches one of the predefined options in an enum. ```typescript // Validate required string validateRequiredString(value, 'fieldName'); // Validate optional number with range validateOptionalNumber(value, 'fieldName', 0, 100); // Validate enum value validateEnum(value, ['option1', 'option2'], 'fieldName'); ``` -------------------------------- ### Configure Recommended Security Headers with Helmet.js Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/SECURITY.md This JavaScript snippet demonstrates how to configure security-related HTTP headers using the Helmet.js middleware in an Express application. It includes examples for setting a Content Security Policy (CSP) to mitigate cross-site scripting (XSS) and other injection attacks, and HTTP Strict Transport Security (HSTS) to enforce HTTPS for future requests. ```javascript // Helmet.js configuration (example) app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], styleSrc: ["'self'", "'unsafe-inline'"], scriptSrc: ["'self'"], imgSrc: ["'self'", "data:", "https:"] } }, hsts: { maxAge: 31536000, includeSubDomains: true, preload: true } })); ``` -------------------------------- ### Define AI Sampling Message Structure in TypeScript Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/constants/README.md This snippet outlines the structure for defining AI sampling messages in TypeScript. Each sampling definition includes a `systemPrompt` to guide the AI, a `schemaName` and `schemaDescription` for clarity, and a `schema` object. The `schema` uses JSON Schema to validate the AI's responses, ensuring they conform to expected data structures. ```typescript export const SAMPLING_NAME = { systemPrompt: 'Instructions for the AI', schemaName: 'response_schema_name', schemaDescription: 'What the schema represents', schema: { // JSON Schema for validating AI responses } }; ``` -------------------------------- ### Utilize Built-in Utility Types in TypeScript Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/types/README.md Examples of using TypeScript's built-in utility types like `Partial`, `Required`, `Pick`, and `Omit` for type transformations. These utilities allow developers to create new types based on existing ones, promoting code reuse and flexibility. ```typescript type PartialPost = Partial; type RequiredFields = Required>; type PostWithoutMeta = Omit; ``` -------------------------------- ### Structure of MCP JWT Token Payload Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/e2e-test/AUTHENTICATION.md Illustrates the JSON structure of the payload embedded within an MCP JWT token. It contains the Reddit username ("sub"), Reddit access and refresh tokens, standard JWT claims like issuance and expiration times, audience, and issuer. This payload enables the server to access Reddit API on behalf of the user. ```json { "sub": "RedditUsername", "reddit_access_token": "...", "reddit_refresh_token": "...", "iat": 1750856286, "exp": 1750942686, "aud": "reddit-mcp-server", "iss": "http://localhost:3000" } ``` -------------------------------- ### Fork and Clone MCP Server Template Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Provides step-by-step instructions for setting up the MCP server template by forking the repository and cloning it locally using standard Git commands. ```bash git clone https://github.com/your-username/your-mcp-server.git cd your-mcp-server ``` -------------------------------- ### Sampling Tool Input Parameters Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Defines the input for the `sampling_example` tool, used for AI-assisted content generation. Parameters include the prompt, maximum tokens for the response, and temperature for creativity. Handled by `src/handlers/tools/sampling-example.ts`. ```typescript { "prompt": "Generate a code example", "maxTokens": 1000, "temperature": 0.7 } ``` -------------------------------- ### systemprompt-mcp-reddit Project Structure Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md A comprehensive overview of the `systemprompt-mcp-reddit` project's directory and file organization. This structure highlights the separation of concerns, including the main entry point, server infrastructure, request handlers, business logic services, constants, type definitions, and utility functions. ```plaintext systemprompt-mcp-reddit/ ├── src/ │ ├── index.ts # Main entry point │ ├── server.ts # HTTP server setup │ ├── server/ # Server infrastructure │ │ ├── mcp.ts # MCP protocol handler with session management │ │ ├── oauth.ts # OAuth 2.1 implementation │ │ ├── middleware.ts # Express middleware (rate limiting, auth) │ │ ├── auth-store.ts # Authentication storage │ │ └── config.ts # Server configuration │ ├── handlers/ # Request handlers │ │ ├── tool-handlers.ts # Tool execution and validation │ │ ├── prompt-handlers.ts # Prompt processing │ │ ├── resource-handlers.ts # Resource management │ │ ├── sampling.ts # AI sampling implementation │ │ ├── notifications.ts # Real-time notifications │ │ ├── callbacks/ # Sampling callback handlers │ │ └── tools/ # Individual tool implementations │ ├── services/ # Business logic │ │ └── reddit/ # Reddit API integration │ ├── constants/ # Configuration and definitions │ │ ├── tools.ts # Tool definitions │ │ ├── resources.ts # Resource definitions │ │ ├── sampling/ # Sampling prompt templates │ │ ├── server/ # Server configuration constants │ │ └── tool/ # Individual tool constants │ ├── types/ # TypeScript definitions │ │ ├── reddit.ts # Reddit-specific types │ │ ├── config.ts # Configuration types │ │ ├── sampling.ts # Sampling types │ │ └── request-context.ts # Request context types │ └── utils/ # Helper functions │ ├── logger.ts # Logging utilities │ ├── reddit-transformers.ts # Reddit data transformers │ └── validation.ts # Validation utilities ├── scripts/ # Development and testing scripts ├── docker-compose.yml # Docker configuration ├── tsconfig.json # TypeScript configuration └── package.json # Project configuration ``` -------------------------------- ### Elicitation Tool Input Parameters Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Specifies the input structure for the `elicitation_example` tool, demonstrating dynamic user input gathering with types like 'input', 'confirm', or 'choice'. This input is processed by `src/handlers/tools/elicitation-example.ts`. ```typescript { "type": "input", // "input", "confirm", "choice" "prompt": "Enter your choice", "options": ["option1", "option2"] // For choice type } ``` -------------------------------- ### Core Files API Reference Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/constants/README.md This section provides an API-like overview of the core files within the Constants directory, detailing their primary responsibilities and key exports. It serves as a reference for understanding the main components that define tools and message handling. ```APIDOC Core Files: tools.ts: Description: Master list of all available tools. Exports: - Array of tool definitions. References: - Tool schemas in /tool directory. Used by: - tool-handlers.ts (for listing available tools). message-handler.ts: Description: Message formatting utilities for Reddit content. Provides: - Structures for posts, comments, and messages. - Consistent output format. ``` -------------------------------- ### Structured Data Tool Input Parameters Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Specifies the input for the `structured_data_example` tool, demonstrating structured data handling with various output formats such as JSON, table, or markdown. This input is processed by `src/handlers/tools/structured-data-example.ts`. ```typescript { "format": "json", // "json", "table", "markdown" "data": { "key": "value" } } ``` -------------------------------- ### Import and Initialize Server with Configuration Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/constants/server/README.md This TypeScript snippet demonstrates how to import the `serverConfig` and `serverCapabilities` objects from the server's constants file. It then uses these imported configurations to initialize a new `Server` instance, setting up the core server behavior and features. ```typescript import { serverConfig, serverCapabilities } from '../constants/server/server-config'; const server = new Server(serverConfig, serverCapabilities); ``` -------------------------------- ### Run systemprompt-mcp-server with npm Scripts Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md This snippet provides commands to run the `systemprompt-mcp-server` using npm scripts. It covers building the TypeScript code, running the compiled server, enabling watch mode for development, and running the server via Docker using an npm script. ```bash # Build the TypeScript code npm run build # Run the built server node build/index.js # Development with watch mode npm run watch # In another terminal: node build/index.js # With Docker npm run docker ``` -------------------------------- ### Key Patterns API Reference Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/constants/README.md This section summarizes the fundamental design patterns enforced across the Constants directory. It covers naming conventions, schema validation methodologies, and prompt engineering best practices, providing a high-level overview of the architectural principles. ```APIDOC Key Patterns: Consistent Naming: Tool constants: TOOL_NAME (uppercase). Sampling constants: SAMPLING_NAME (uppercase). Schema properties: camelCase. Schema Validation: Standard: JSON Schema Draft 7. Features: - Required fields clearly marked. - Descriptions for all properties. - Type constraints and validations. - Examples where helpful. Prompt Engineering: Practices: - Clear instructions. - Expected format specification. - Examples when needed. - Constraints and guidelines. ``` -------------------------------- ### OAuth Initial Connection Flow Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/server/README.md Illustrates the sequence of steps for a client to establish an initial connection and obtain a JWT token via Reddit OAuth. ```text Client → /oauth/authorize → Reddit OAuth → /oauth/callback → JWT Token ``` -------------------------------- ### Best Practices API Reference Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/constants/README.md This section outlines recommended best practices for designing schemas, engineering prompts, and implementing validation within the Constants directory. It provides guidelines to ensure maintainability, clarity, and robustness of the definitions. ```APIDOC Best Practices: Schema Design: - Make required fields minimal. - Provide sensible defaults. - Use clear, descriptive names. - Add helpful descriptions. Prompt Design: - Be specific about output format. - Include examples for complex tasks. - Set clear boundaries. - Guide tone and style. Validation: - Use strict type checking. - Validate string formats. - Set reasonable limits. - Provide clear error messages. ``` -------------------------------- ### Build Docker Image for MCP Server Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Command to build a Docker image for the `systemprompt-mcp-reddit` server. This creates a portable image containing the application and its dependencies. ```bash # Build image docker build -t systemprompt-mcp-reddit . ``` -------------------------------- ### Build and Run Docker Containers with Docker Compose Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md The recommended command for quickly building and running the MCP server using `docker-compose`. This simplifies the orchestration of multiple Docker containers if defined in the `docker-compose.yml`. ```bash # Build and run with docker-compose (recommended) npm run docker:build-and-run ``` -------------------------------- ### Create Initial .env File for Reddit API Configuration Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md This bash command creates an initial `.env` file with placeholder values for Reddit API client ID, client secret, and a JWT secret. These are essential for the server to connect to Reddit and secure user sessions. ```bash cat > .env << EOF REDDIT_CLIENT_ID=your_reddit_client_id REDDIT_CLIENT_SECRET=your_reddit_client_secret JWT_SECRET=any_random_string_here EOF ``` -------------------------------- ### Server Configuration API Reference Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/constants/README.md This section describes the server-level configuration and constants. It outlines the metadata and capabilities of the MCP server, including protocol versions, feature declarations, and session/rate limiting configurations. ```APIDOC Server Configuration (/server): server-config.ts: Description: MCP server metadata and capabilities. Includes: - Protocol version and feature declarations. - Session and rate limiting configuration. ``` -------------------------------- ### Client and Server Interaction for AI Sampling Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Illustrates the multi-step process of AI-assisted content generation, from the client's initial request to the server's initiation of a sampling operation and the subsequent handling of the AI's response. This process adheres to the MCP specification for sampling. ```typescript // 1. Client requests AI assistance await client.callTool("sampling_example", { prompt: "Analyze this subreddit and suggest actions", maxTokens: 1000, temperature: 0.7 }); // 2. Server initiates sampling for content generation const samplingRequest = { method: "sampling/createMessage", params: { messages: [{ role: "user", content: { type: "text", text: "Analyze this subreddit and suggest actions" } }], maxTokens: 1000, temperature: 0.7, _meta: { callback: "suggest_action" } } }; // 3. AI generates content // 4. Callback processes the response // 5. Client receives the final result ``` -------------------------------- ### Tool: get_channel Parameters Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Outlines the JSON parameters for the `get_channel` tool, designed to retrieve posts from a specified subreddit. It allows users to define the `subreddit` and choose a `sort` order from 'hot', 'new', or 'controversial' to organize the fetched posts. ```json { "subreddit": "programming", "sort": "hot" // "hot", "new", or "controversial" } ``` -------------------------------- ### Define a New TypeScript Service Class with Singleton Pattern Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/services/README.md This snippet provides a template for creating a new service class, incorporating the Singleton pattern for global access. It outlines the basic structure including the `getInstance` method for singleton implementation and a placeholder for specific service operations. ```typescript export class MyService { private static instance: MyService; public static getInstance(): MyService { // Singleton implementation } public async myOperation(): Promise { // Operation implementation } } ``` -------------------------------- ### Tool Definitions API Reference Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/constants/README.md This section details the structure and purpose of individual tool definition files. Each file defines a tool's schema and metadata, categorized by their functionality. This serves as a reference for understanding available tools and their input requirements. ```APIDOC Tool Definitions (/tool): Description: Each file defines a tool's schema and metadata. Categories: Search and Discovery Tools: search-reddit.ts: Search parameters and description. get-channel.ts: Subreddit info retrieval schema. Content Retrieval Tools: get-post.ts: Post fetching parameters. get-comment.ts: Comment thread schema. get-notifications.ts: Notification retrieval. Content Creation Tools: create-post.ts: Post submission schema. create-comment.ts: Comment creation parameters. create-message.ts: Private message schema. ``` -------------------------------- ### Run Docker Image with Environment Variables Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Command to run the previously built Docker image, mapping port 3001 and passing required Reddit client and JWT secrets as environment variables. This demonstrates how to configure the running container. ```bash docker run -p 3001:3001 \ -e REDDIT_CLIENT_ID=your_id \ -e REDDIT_CLIENT_SECRET=your_secret \ -e JWT_SECRET=your_jwt_secret \ systemprompt-mcp-reddit ``` -------------------------------- ### Full .env Configuration for systemprompt-mcp-server Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md This code block illustrates a complete `.env` file configuration for the `systemprompt-mcp-server`. It includes required Reddit API credentials and JWT secret, along with optional settings for port, OAuth issuer, redirect URL, user agent, Reddit username, and logging level. ```bash # Required for Reddit API REDDIT_CLIENT_ID=your_reddit_client_id REDDIT_CLIENT_SECRET=your_reddit_client_secret JWT_SECRET=your_jwt_secret # Secret for JWT signing # Optional PORT=3000 # Server port (default: 3000) OAUTH_ISSUER=http://localhost:3000 # OAuth issuer URL REDIRECT_URL=http://localhost:3000/oauth/reddit/callback # OAuth redirect REDDIT_USER_AGENT=linux:systemprompt-mcp-reddit:v2.0.0 # Reddit user agent REDDIT_USERNAME=your_reddit_username # Your Reddit username (optional) LOG_LEVEL=debug # Logging level (debug, info, warn, error) ``` -------------------------------- ### TypeScript New Utility File Template Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/utils/README.md Provides a basic template for creating a new utility file, `my-utility.ts`, demonstrating standard practices for function definition. It includes JSDoc comments for documenting the function's purpose, parameters, and return type, promoting clear and maintainable code. ```typescript // my-utility.ts /** * Does something useful * @param input - The input data * @returns The processed result */ export function myUtility(input: string): string { // Implementation } ``` -------------------------------- ### Execute Unit and End-to-End Tests Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Commands to run all unit tests and end-to-end tests for the MCP server. It explicitly notes the requirement for OAuth tokens to be present in the `.env` file for tests that interact with Reddit. ```bash # Run all tests (requires OAuth tokens in .env) npm run test # Run end-to-end tests npm run e2e ``` -------------------------------- ### Add OAuth Access Token to .env File Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md This bash command appends the obtained OAuth access token to the existing `.env` file. This token is crucial for authenticating the server's Reddit session after the initial OAuth flow. ```bash echo "OAUTH_ACCESS_TOKEN=your_oauth_token_here" >> .env ``` -------------------------------- ### Manually Test MCP OAuth Initialization Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md A `curl` command demonstrating how to manually initiate the MCP `initialize` endpoint. This can be used to test the server's response and check if authentication details are required or provided. ```bash curl -X POST http://localhost:3000/mcp/v1/initialize \ -H "Content-Type: application/json" \ -d '{"protocolVersion": "2024-11-05", "capabilities": {}}' ``` -------------------------------- ### Run MCP Inspector Compatibility Test Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md This command executes the MCP Inspector compatibility test, verifying the server's full support for features like OAuth 2.1, tools, prompts, sampling, and notifications. It allows developers to test the server's adherence to the MCP specification and ensure proper functionality. ```Shell npm run inspector ``` -------------------------------- ### Server Environment Variables Reference Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/CODE_STRUCTURE_GUIDE.md Lists and describes the required and optional environment variables used to configure the SystemPrompt MCP server, including sensitive keys and default values. ```APIDOC Environment Variables: Required: - `REDDIT_CLIENT_ID`: Reddit OAuth client ID - `REDDIT_CLIENT_SECRET`: Reddit OAuth client secret - `JWT_SECRET`: Secret for JWT signing Optional: - `PORT`: Server port (default: 3000) - `OAUTH_ISSUER`: OAuth issuer URL (default: http://localhost:3000) - `REDIRECT_URL`: OAuth redirect URL (default: auto-generated) - `REDDIT_USER_AGENT`: Reddit API user agent string - `REDDIT_USERNAME`: Reddit username for logging - `NODE_ENV`: Environment (development/production) ``` -------------------------------- ### Tool: search_reddit Parameters Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Defines the JSON parameters for the `search_reddit` tool, enabling users to perform searches across Reddit. It supports specifying a query, an optional subreddit, sorting criteria (relevance, hot, new, top), a time range, and a limit on the number of results. ```json { "query": "typescript MCP", "subreddit": "programming", // Optional specific subreddit "sort": "relevance", "time": "week", "limit": 10 } ``` -------------------------------- ### Configure MCP Server Settings Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Shows how to update the `serverConfig` and `serverCapabilities` objects in `src/constants/server/server-config.ts`. This configuration defines the server's name, version, description, and its supported capabilities like tools, prompts, resources, and sampling. ```typescript export const serverConfig = { name: "your-mcp-server", version: "1.0.0", description: "Your MCP server description" }; export const serverCapabilities = { tools: {}, prompts: {}, resources: {}, sampling: {} }; ``` -------------------------------- ### MCP Session Connection Flow Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/server/README.md Describes how a client, using a JWT, initiates an MCP session and obtains an MCP server instance. ```text Client (with JWT) → /mcp → Session Creation → MCP Server Instance ``` -------------------------------- ### Restart Docker Server with OAuth Token Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md This command restarts the `systemprompt-mcp-server` Docker container, now including the newly added OAuth access token from the `.env` file. This enables authenticated Reddit API calls. ```bash docker run -it --rm \ -p 3000:3000 \ --env-file .env \ node:20-slim \ npx @systemprompt/systemprompt-mcp-server ``` -------------------------------- ### Authentication Storage Module (server/auth-store.ts) Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/CODE_STRUCTURE_GUIDE.md Outlines the responsibilities of the authentication storage module, including credential storage, thread-safe access, and its role in callback handlers. ```APIDOC Authentication Storage (server/auth-store.ts): - Stores Reddit credentials per session - Provides thread-safe access to auth info - Used by callback handlers for authenticated operations - Simple in-memory storage for development ``` -------------------------------- ### Create New Tool Schema File in TypeScript Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/constants/README.md This snippet demonstrates how to create a new tool schema file. The file exports a constant object representing the tool, including its unique name, a description, and its `inputSchema` definition. This file should be placed in the `/tool/` directory. ```typescript // /tool/my-new-tool.ts export const MY_NEW_TOOL = { name: 'my_new_tool', description: 'What it does', inputSchema: { ... } }; ``` -------------------------------- ### Illustrate Facade Pattern for Service Coordination in TypeScript Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/services/README.md This snippet shows the Facade design pattern, where a main service (e.g., `RedditService`) provides a simplified interface to a complex subsystem of multiple specialized services (e.g., `RedditAuthService`, `RedditPostService`). It coordinates operations across these services, abstracting their underlying complexity. ```typescript class RedditService { private authService: RedditAuthService; private postService: RedditPostService; // Coordinates multiple services for complex operations } ``` -------------------------------- ### TypeScript New Utility Test File Template Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/utils/README.md Outlines the basic structure for a unit test file, `__tests__/my-utility.test.ts`, for a newly created utility function. It demonstrates how to use a `describe` block to group tests and an `it` block to define a specific test case, ensuring the utility functions as expected. ```typescript // __tests__/my-utility.test.ts describe('myUtility', () => { it('should process input correctly', () => { expect(myUtility('test')).toBe('expected'); }); }); ``` -------------------------------- ### Implement Singleton Pattern for TypeScript Services Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/services/README.md This code demonstrates the Singleton design pattern, ensuring that a service class has only one instance and provides a global point of access to it. This pattern is commonly used in services to manage shared resources or maintain a single point of control for external interactions. ```typescript class MyService { private static instance: MyService; public static getInstance(): MyService { if (!MyService.instance) { MyService.instance = new MyService(); } return MyService.instance; } } ``` -------------------------------- ### Define a New Tool for MCP Server Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Illustrates how to define a new tool using the `ToolDefinition` interface in TypeScript. This includes defining the tool's schema (name, description, input parameters) and its asynchronous handler function for implementation. ```typescript // src/handlers/tools/your-tool.ts export const yourTool: ToolDefinition = { schema: { name: "your_tool", description: "What your tool does", inputSchema: { type: "object", properties: { // Your parameters } } }, handler: async (params, context) => { // Tool implementation } }; ``` -------------------------------- ### OAuth 2.1 Provider Module (server/oauth.ts) Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/CODE_STRUCTURE_GUIDE.md Documents the core functionalities of the OAuth 2.1 provider module, including authorization flow, token management, and integration with Reddit OAuth. ```APIDOC OAuth 2.1 Provider (server/oauth.ts): - Implements complete authorization flow with PKCE - Manages JWT tokens and refresh logic - Provides auth middleware for request validation - Handles Reddit OAuth integration - Supports well-known endpoints for metadata ``` -------------------------------- ### Create New AI Sampling Definition in TypeScript Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/constants/README.md This snippet illustrates the creation of a new sampling definition file. It exports a constant object containing the `systemPrompt` for AI guidance and the `schema` for validating AI responses. This file should reside in the `/sampling/` directory. ```typescript // /sampling/my-operation.ts export const MY_OPERATION_SAMPLING = { systemPrompt: 'Generate a ...', schema: { ... } }; ``` -------------------------------- ### Save OAuth Tokens to .env for Persistent Testing Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Illustrates how to add generated Reddit OAuth access and refresh tokens to the `.env` file. This step is essential for persistent testing, allowing subsequent test runs to authenticate without manual intervention after the initial OAuth flow. ```bash # Add these to your .env after completing OAuth REDDIT_ACCESS_TOKEN=your_access_token REDDIT_REFRESH_TOKEN=your_refresh_token ``` -------------------------------- ### Server Environment Variable Configuration Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/server/README.md Required and optional environment variables for configuring the server, including OAuth credentials, JWT secret, and server port. ```bash REDDIT_CLIENT_ID=your_client_id REDDIT_CLIENT_SECRET=your_client_secret JWT_SECRET=your_jwt_secret_min_32_chars ``` ```bash PORT=3000 OAUTH_ISSUER=https://your-domain.com ``` -------------------------------- ### Tool: get_post Parameters Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Specifies the JSON parameter for the `get_post` tool, which is used to fetch a specific Reddit post. The tool requires a single parameter, `id`, which must be the unique identifier of the desired Reddit post. ```json { "id": "post_id_here" // Reddit post ID } ``` -------------------------------- ### MCP Subsequent Request Flow Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/src/server/README.md Outlines the process for handling subsequent client requests by routing them to an existing MCP session. ```text Client → /mcp (with session ID) → Route to Existing Session → Handle Request ``` -------------------------------- ### Systemprompt MCP Server Layered Architecture Diagram Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Illustrates the high-level layered architecture of the Systemprompt MCP Server, detailing the separation between Client, MCP Server, Handler, and Service layers, along with their key internal components and communication protocols. ```text ┌─────────────────────────────────────────────────────────┐ │ Client Application │ │ (systemprompt.io) │ └────────────────────────┬────────────────────────────────┘ │ MCP Protocol ┌────────────────────────┴────────────────────────────────┐ │ MCP Server Layer │ │ ┌─────────────┐ ┌─────────────┐ ┌────────────────┐ │ │ │ OAuth 2.1 │ │ Session │ │ Notification │ │ │ │ Handler │ │ Manager │ │ Manager │ │ │ └─────────────┘ └─────────────┘ └────────────────┘ │ └────────────────────────┬────────────────────────────────┘ │ ┌────────────────────────┴────────────────────────────────┐ │ Handler Layer │ │ ┌─────────────┐ ┌─────────────┐ ┌────────────────┐ │ │ │ Tools │ │ Resources │ │ Sampling │ │ │ │ Handler │ │ Handler │ │ Handler │ │ │ └─────────────┘ └─────────────┘ └────────────────┘ │ └────────────────────────┬────────────────────────────────┘ │ ┌────────────────────────┴────────────────────────────────┐ │ Service Layer │ │ ┌─────────────┐ ┌─────────────┐ ┌────────────────┐ │ │ │ Reddit │ │ Auth │ │ Fetch │ │ │ │ Service │ │ Service │ │ Service │ │ │ └─────────────┘ └─────────────┘ └────────────────┘ │ └─────────────────────────────────────────────────────────┘ ``` -------------------------------- ### MCP Logging Tool Input Parameters Source: https://github.com/systempromptio/systemprompt-mcp-server/blob/main/README.md Specifies the input for the `mcp_logging` tool, allowing the server to log messages with different severity levels (debug, info, warning, error) and include additional contextual data. The handler is located at `src/handlers/tools/logging.ts`. ```typescript { "level": "info", // "debug", "info", "warning", "error" "message": "Debug message", "data": { "additional": "context" } } ```