Introduction
The Model Context Protocol (MCP) standardizes how applications send structured context to AI models. In 2026 it is essential for avoiding hallucinations and improving response consistency. The protocol lets you define clear rules around data, history, and constraints. It functions like a contract between your application and the model. Learning MCP now gives you a competitive advantage when building dependable AI applications.
Prerequisites
- Node.js 20 or higher
- Basic TypeScript knowledge
- An editor such as VS Code
- An account with an MCP-compatible model provider
Installing Dependencies
npm init -y
npm install @mcp/sdk typescript @types/node
npx tsc --initThis command initializes the project and installs the official MCP SDK along with TypeScript. The SDK automatically handles protocol formatting and validation.
Creating the MCP Configuration File
{
"protocolVersion": "1.0",
"contextSchema": {
"type": "object",
"properties": {
"userId": { "type": "string" },
"sessionHistory": { "type": "array" }
},
"required": ["userId"]
},
"maxContextTokens": 8000
}This JSON file defines the expected context structure. It tells the model which fields are required and limits context size to prevent overflows.
Context Structure Explained
The configuration file acts as a validation schema. Each property specifies the allowed data type. This prevents sending unnecessary or malformed information to the model.
Implementing the MCP Client
import { MCPClient } from '@mcp/sdk';
const client = new MCPClient({
endpoint: 'https://api.example.com/mcp',
apiKey: process.env.MCP_API_KEY
});
export async function sendContext(context: any) {
const validated = await client.validateContext(context);
return client.sendContext(validated);
}The MCP client connects to the endpoint and automatically validates context before sending. The sendContext function ensures only compliant data is transmitted.
Creating the Context Handler
import { ContextHandler } from '@mcp/sdk';
export const handler = new ContextHandler({
schema: require('../mcp.config.json').contextSchema,
onValidate: (data) => {
if (!data.userId) throw new Error('userId requis');
return data;
}
});This handler intercepts and validates every context before transmission. It centralizes validation rules and simplifies maintenance.
Integration in the Main Application
import { sendContext } from './mcp-client';
import { handler } from './context-handler';
async function main() {
const context = {
userId: 'user_123',
sessionHistory: ['Bonjour', 'Comment allez-vous ?']
};
const validated = await handler.process(context);
const response = await sendContext(validated);
console.log(response);
}
main();The main file combines the handler and client. It prepares a valid context and sends it to the model via MCP.
Testing the MCP Connection
npm run build
node dist/index.jsThis command compiles TypeScript and runs the script. Verify that the model response respects the schema defined in mcp.config.json.
Best Practices
- Always validate context before sending with the handler
- Limit token count to reduce costs
- Version your mcp.config.json file
- Log validation errors
- Test with real contexts from the beginning
Common Mistakes to Avoid
- Forgetting to define required fields in the schema
- Sending untyped data without validation
- Ignoring the maxContextTokens limit
- Not handling MCP endpoint connection errors
Going Further
Deepen your skills with our complete courses on modern AI protocols. Discover our Learni courses.