Skip to content

Instantly share code, notes, and snippets.

@crazyrabbitLTC
Created December 31, 2024 05:00
Show Gist options
  • Save crazyrabbitLTC/177f0f06738f6807751178a1d0547deb to your computer and use it in GitHub Desktop.
Save crazyrabbitLTC/177f0f06738f6807751178a1d0547deb to your computer and use it in GitHub Desktop.
MCP Server Style Guide
# MCP Server Style Guide and Standards
## Project Structure
```
project/
├── src/
│ ├── services/ # Core service implementations
│ │ └── service.ts # Main service class
│ ├── index.ts # Entry point and exports
│ └── server.ts # MCP server implementation
├── .env.example # Example environment variables
├── .gitignore # Git ignore patterns
├── LICENSE # MIT License
├── package.json # Project configuration
├── README.md # Project documentation
└── tsconfig.json # TypeScript configuration
```
## Code Organization
### 1. Service Layer
- Implement core business logic in a dedicated service class
- Keep service methods pure and testable
- Handle all external API calls and data processing
- Define clear interfaces for all data types
Example:
```typescript
static getOpenAIFunctionDefinitions() {
return [{
name: "get_historical_data",
description: "Get historical data for a specific date range",
parameters: {
type: "object",
properties: {
start_date: {
type: "string",
description: "Start date in YYYY-MM-DD format (e.g., '2024-01-01')",
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
},
end_date: {
type: "string",
description: "End date in YYYY-MM-DD format (e.g., '2024-12-31')",
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
}
},
required: ["start_date", "end_date"]
}
}];
}
// Example of proper timestamp handling in implementation
async function getHistoricalData(startDate: string, endDate: string) {
// Convert human-readable dates to Unix timestamps in the implementation
const startTimestamp = Math.floor(new Date(startDate).getTime() / 1000);
const endTimestamp = Math.floor(new Date(endDate).getTime() / 1000);
// ... perform data retrieval ...
// Return both formats in response
return {
data: retrievedData,
timeRange: {
start: {
unix: startTimestamp,
human_readable: startDate,
},
end: {
unix: endTimestamp,
human_readable: endDate,
}
}
};
}
// Original example:
```typescript
export interface ServiceConfig {
apiKey: string;
baseUrl?: string;
}
export class Service {
private readonly baseUrl: string;
constructor(private config: ServiceConfig) {
this.baseUrl = config.baseUrl || "https://api.default.com";
}
async getData(): Promise<DataType> {
// Implementation
}
}
```
### 2. Server Implementation
- Separate MCP protocol handling from business logic
- Use clear request/response schemas
- Implement proper error handling
- Support both MCP and OpenAI function definitions
## Coding Standards
### Timestamp Handling
1. Accept human-readable dates in function inputs (YYYY-MM-DD, YYYY-MM-DD HH:mm:ss)
2. Handle Unix timestamp conversions in server code, not in LLM
3. When returning timestamps to LLMs, provide both Unix and human-readable formats
4. Document any precision loss in timestamp conversions
5. Use ISO 8601 format for consistency when possible
Example:
```typescript
interface TimestampResponse {
unix_timestamp: number;
human_readable: string;
precision_note?: string; // Include if there's precision loss
}
function getTimestampData(): TimestampResponse {
const now = new Date();
return {
unix_timestamp: Math.floor(now.getTime() / 1000),
human_readable: now.toISOString(),
precision_note: "Milliseconds truncated to seconds"
};
}
```
### TypeScript Best Practices
1. Use strict typing
2. Define interfaces for all data structures
3. Use enums for fixed sets of values
4. Leverage TypeScript's advanced features appropriately
### Error Handling
1. Define custom error types
2. Use descriptive error messages
3. Include appropriate error codes
4. Provide context in error responses
Example:
```typescript
class ServiceError extends Error {
constructor(
message: string,
public code: string,
public status: number = 500
) {
super(message);
this.name = 'ServiceError';
}
}
```
### Async/Await
1. Always use async/await over promises
2. Implement proper error boundaries
3. Handle timeouts appropriately
4. Clean up resources in finally blocks
### Configuration
1. Use environment variables for configuration
2. Provide clear documentation for all config options
3. Include validation for configuration values
4. Support reasonable defaults
## MCP Implementation Guidelines
### 1. Tool Definitions
- Provide clear, concise tool descriptions
- Use specific, well-defined input schemas
- Include examples in descriptions
- Support both MCP and OpenAI formats
Example:
```typescript
{
name: "get-data",
description: "Retrieve data with specific parameters",
inputSchema: {
type: "object",
properties: {
id: {
type: "string",
description: "Unique identifier"
},
filter: {
type: "string",
enum: ["all", "active", "archived"],
description: "Filter type"
}
},
required: ["id"]
}
}
```
### 2. Resource Handling
- Implement clear resource URIs
- Handle resource updates efficiently
- Support proper MIME types
- Implement pagination where needed
### 3. Error Responses
- Use standard error codes
- Provide helpful error messages
- Include relevant context
- Support proper error handling in clients
## Security Standards
### 1. Authentication
- Validate all API keys
- Implement proper token handling
- Use secure environment variables
- Follow security best practices
### 2. Input Validation
- Validate all input parameters
- Sanitize user inputs
- Prevent injection attacks
- Implement rate limiting
### 3. Resource Access
- Implement proper access controls
- Validate resource paths
- Prevent path traversal
- Handle permissions appropriately
## Testing Guidelines
### 1. Unit Tests
- Test all service methods
- Mock external dependencies
- Test error conditions
- Achieve high coverage
### 2. Integration Tests
- Test complete workflows
- Verify error handling
- Test rate limiting
- Validate resource access
## Documentation Standards
### 1. Code Documentation
- Document all public methods
- Include usage examples
- Document error conditions
- Use JSDoc format
Example:
```typescript
/**
* Retrieve data from the service
* @param {string} id - Unique identifier
* @param {FilterOptions} filter - Optional filter parameters
* @returns {Promise<Data>} Retrieved data
* @throws {ServiceError} When retrieval fails
*/
async getData(id: string, filter?: FilterOptions): Promise<Data>
```
### 2. README Documentation
- Clear installation instructions
- Usage examples
- Configuration options
- Troubleshooting guide
## OpenAI Function Definitions
### 1. Schema Structure
- Always use human-readable date formats in schema definitions
- Include clear format specifications in descriptions
- Handle timestamp conversions in implementation, not in function definitions
```typescript
static getOpenAIFunctionDefinitions() {
return [{
name: "function_name",
description: `Clear description of the function's purpose`,
parameters: {
type: "object",
properties: {
param1: {
type: "string",
description: "Parameter description"
}
},
required: ["param1"]
}
}];
}
```
### 2. Function Implementation
- Match schema definitions exactly
- Handle all error cases
- Provide clear responses
- Include proper validation
## Deployment Guidelines
### 1. Environment Setup
- Document all requirements
- Include dependency list
- Specify version requirements
- Provide configuration examples
### 2. Build Process
- Include clear build instructions
- Document all build steps
- Handle different environments
- Include proper error handling
## Maintenance Standards
### 1. Versioning
- Follow semantic versioning
- Document breaking changes
- Maintain changelog
- Handle deprecations properly
### 2. Updates
- Regular dependency updates
- Security patch process
- Documentation updates
- Change notification process
## Quality Assurance
### 1. Code Quality
- Use ESLint/Prettier
- Follow consistent style
- Regular code reviews
- Maintain test coverage
### 2. Performance
- Monitor response times
- Handle rate limiting
- Implement caching
- Regular performance testing
## Git Workflow
### 1. Commit Standards
- Clear commit messages
- Logical commit grouping
- Reference issues/tickets
- Include tests with changes
### 2. Branch Strategy
- Feature branches
- Release process
- Hotfix handling
- Version tagging
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment