MCP Server Development Skill
Context
This skill applies when:
- Implementing MCP protocol tools, resources, and prompts
- Creating MCP server handlers for European Parliament data
- Designing tool input/output schemas
- Implementing resource URI patterns
- Creating prompt templates for AI assistants
- Handling MCP protocol errors and edge cases
- Testing MCP server implementations
- Optimizing MCP tool performance
MCP (Model Context Protocol) is the foundation of this server. All data access must follow MCP specification patterns to ensure compatibility with MCP clients.
Rules
- Follow MCP Specification: Implement all handlers according to MCP protocol specification
- Validate Tool Inputs: Use Zod schemas to validate all tool inputs before processing
- Return Structured Responses: Always return MCP-compliant response structures with
content array
- Handle Errors Gracefully: Catch errors and return safe error messages (never expose internal details)
- Use Type Safety: Leverage TypeScript types for all MCP handlers and request/response objects
- Implement Resources with URIs: Use consistent URI patterns (e.g.,
ep://meps/{id})
- Provide Tool Descriptions: Write clear, concise descriptions for all tools, resources, and prompts
- Document Input Schemas: Use JSON Schema in tool listings to document expected inputs
- Log MCP Operations: Log all tool invocations, resource accesses for audit trails
- Test MCP Handlers: Write comprehensive tests for all MCP tools and resources
Examples
✅ Good Pattern: MCP Tool Implementation
import { z } from 'zod';
import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
// Input schema with validation
const SearchMEPsInputSchema = z.object({
country: z.string().length(2).regex(/^[A-Z]{2}$/).optional(),
limit: z.number().int().min(1).max(100).default(20),
}).strict();
// Tool handler
export async function handleSearchMEPs(request: typeof CallToolRequestSchema._type) {
const input = SearchMEPsInputSchema.parse(request.params.arguments);
try {
const meps = await searchMEPs(input);
return {
content: [{
type: "text",
text: JSON.stringify({ count: meps.length, meps }, null, 2)
}]
};
} catch (error) {
console.error('[MCP Tool Error] search_meps:', error);
throw new Error('Failed to search MEPs. Please try again.');
}
}
// Tool registration
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [{
name: "search_meps",
description: "Search Members of the European Parliament by filters",
inputSchema: {
type: "object",
properties: {
country: { type: "string", pattern: "^[A-Z]{2}$" },
limit: { type: "number", minimum: 1, maximum: 100, default: 20 },
},
},
}],
}));
✅ Good Pattern: MCP Resource Implementation
// Resource URI pattern
const MEP_RESOURCE_TEMPLATE = "ep://meps/{id}";
// List resources
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
resources: [{
uri: MEP_RESOURCE_TEMPLATE,
name: "European Parliament Member",
description: "Detailed MEP information",
mimeType: "application/json",
}],
}));
// Read resource
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const uri = request.params.uri;
const match = uri.match(/^ep:\/\/meps\/(\d+)$/);
if (!match) {
throw new Error(`Invalid MEP resource URI: ${uri}`);
}
const mepId = parseInt(match[1], 10);
const mep = await getMEPById(mepId);
return {
contents: [{
uri,
mimeType: "application/json",
text: JSON.stringify(mep, null, 2),
}],
};
});
Anti-Patterns
❌ Bad: No Input Validation
// NEVER - no validation!
async function bad(request: any) {
const data = await fetch(request.params.arguments.url); // Injection risk!
return { content: [{ type: "text", text: data }] };
}
❌ Bad: Exposing Internal Errors
// NEVER - exposes internals!
async function bad(request: any) {
try {
return await process(request);
} catch (error) {
throw error; // Exposes stack trace!
}
}
ISMS Compliance
- SC-002: Input validation for all tool parameters (Zod schemas)
- AU-002: Audit logging for tool invocations (personal-data tools especially)
- AC-003: Rate limiting and access control (
EP_RATE_LIMIT)
- SC-001: Safe output — no raw upstream errors, sanitised responses
Policy References
Primary:
Related:
1---2name: mcp-server-development3description: MCP protocol patterns, tool implementation, resource handlers, prompt templates, and error handling for Model Context Protocol servers4license: MIT5metadata:6 source: https://skillmd.com/skills/hack23/mcp-server-development7---89# MCP Server Development Skill1011## Context1213This skill applies when:14- Implementing MCP protocol tools, resources, and prompts15- Creating MCP server handlers for European Parliament data16- Designing tool input/output schemas17- Implementing resource URI patterns18- Creating prompt templates for AI assistants19- Handling MCP protocol errors and edge cases20- Testing MCP server implementations21- Optimizing MCP tool performance2223MCP (Model Context Protocol) is the foundation of this server. All data access must follow MCP specification patterns to ensure compatibility with MCP clients.2425## Rules26271. **Follow MCP Specification**: Implement all handlers according to [MCP protocol specification](https://spec.modelcontextprotocol.io/)282. **Validate Tool Inputs**: Use Zod schemas to validate all tool inputs before processing293. **Return Structured Responses**: Always return MCP-compliant response structures with `content` array304. **Handle Errors Gracefully**: Catch errors and return safe error messages (never expose internal details)315. **Use Type Safety**: Leverage TypeScript types for all MCP handlers and request/response objects326. **Implement Resources with URIs**: Use consistent URI patterns (e.g., `ep://meps/{id}`)337. **Provide Tool Descriptions**: Write clear, concise descriptions for all tools, resources, and prompts348. **Document Input Schemas**: Use JSON Schema in tool listings to document expected inputs359. **Log MCP Operations**: Log all tool invocations, resource accesses for audit trails3610. **Test MCP Handlers**: Write comprehensive tests for all MCP tools and resources3738## Examples3940### ✅ Good Pattern: MCP Tool Implementation4142```typescript43import { z } from 'zod';44import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';4546// Input schema with validation47const SearchMEPsInputSchema = z.object({48 country: z.string().length(2).regex(/^[A-Z]{2}$/).optional(),49 limit: z.number().int().min(1).max(100).default(20),50}).strict();5152// Tool handler53export async function handleSearchMEPs(request: typeof CallToolRequestSchema._type) {54 const input = SearchMEPsInputSchema.parse(request.params.arguments);55 56 try {57 const meps = await searchMEPs(input);58 59 return {60 content: [{61 type: "text",62 text: JSON.stringify({ count: meps.length, meps }, null, 2)63 }]64 };65 } catch (error) {66 console.error('[MCP Tool Error] search_meps:', error);67 throw new Error('Failed to search MEPs. Please try again.');68 }69}7071// Tool registration72server.setRequestHandler(ListToolsRequestSchema, async () => ({73 tools: [{74 name: "search_meps",75 description: "Search Members of the European Parliament by filters",76 inputSchema: {77 type: "object",78 properties: {79 country: { type: "string", pattern: "^[A-Z]{2}$" },80 limit: { type: "number", minimum: 1, maximum: 100, default: 20 },81 },82 },83 }],84}));85```8687### ✅ Good Pattern: MCP Resource Implementation8889```typescript90// Resource URI pattern91const MEP_RESOURCE_TEMPLATE = "ep://meps/{id}";9293// List resources94server.setRequestHandler(ListResourcesRequestSchema, async () => ({95 resources: [{96 uri: MEP_RESOURCE_TEMPLATE,97 name: "European Parliament Member",98 description: "Detailed MEP information",99 mimeType: "application/json",100 }],101}));102103// Read resource104server.setRequestHandler(ReadResourceRequestSchema, async (request) => {105 const uri = request.params.uri;106 const match = uri.match(/^ep:\/\/meps\/(\d+)$/);107 108 if (!match) {109 throw new Error(`Invalid MEP resource URI: ${uri}`);110 }111 112 const mepId = parseInt(match[1], 10);113 const mep = await getMEPById(mepId);114 115 return {116 contents: [{117 uri,118 mimeType: "application/json",119 text: JSON.stringify(mep, null, 2),120 }],121 };122});123```124125## Anti-Patterns126127### ❌ Bad: No Input Validation128```typescript129// NEVER - no validation!130async function bad(request: any) {131 const data = await fetch(request.params.arguments.url); // Injection risk!132 return { content: [{ type: "text", text: data }] };133}134```135136### ❌ Bad: Exposing Internal Errors137```typescript138// NEVER - exposes internals!139async function bad(request: any) {140 try {141 return await process(request);142 } catch (error) {143 throw error; // Exposes stack trace!144 }145}146```147148## ISMS Compliance149150- **SC-002**: Input validation for all tool parameters (Zod schemas)151- **AU-002**: Audit logging for tool invocations (personal-data tools especially)152- **AC-003**: Rate limiting and access control (`EP_RATE_LIMIT`)153- **SC-001**: Safe output — no raw upstream errors, sanitised responses154155### Policy References156157**Primary:**158159- [Secure Development Policy](https://github.com/Hack23/ISMS-PUBLIC/blob/main/Secure_Development_Policy.md) — Input validation, audit logging, secure error handling160- [OWASP LLM Security Policy](https://github.com/Hack23/ISMS-PUBLIC/blob/main/OWASP_LLM_Security_Policy.md) — Prompt-injection resistance in tool descriptions, output filtering161162**Related:**163164- [Information Security Policy](https://github.com/Hack23/ISMS-PUBLIC/blob/main/Information_Security_Policy.md)165- [Privacy Policy](https://github.com/Hack23/ISMS-PUBLIC/blob/main/Privacy_Policy.md) — MEP personal-data tools166- [Access Control Policy](https://github.com/Hack23/ISMS-PUBLIC/blob/main/Access_Control_Policy.md) — Least privilege on tool capabilities167- [AI Policy](https://github.com/Hack23/ISMS-PUBLIC/blob/main/AI_Policy.md) — Responsible MCP-tool integration with LLMs168- [Open Source Policy](https://github.com/Hack23/ISMS-PUBLIC/blob/main/Open_Source_Policy.md) — Attribution in tool output