Code Examples
This page provides real-world code examples that demonstrate common patterns and best practices for creating MCP tools. Each example includes the complete code and detailed explanations of how it works.
Example 1: Simple Data Transformation
This is the simplest type of tool - it takes input data, transforms it, and returns the result. No external APIs, no complex logic, just straightforward data processing.
async function execute(params, config) { const { text } = params; // Transform text to uppercase const result = text.toUpperCase(); return { success: true, data: { transformed: result } }; }How It Works
Extracts the parameter - Uses destructuring to get the "text" parameter from params
Transforms the data - Converts the text to uppercase using JavaScript's toUpperCase() method
Returns the result - Returns a structured response with the transformed data
Parameter Schema
{ "text": { "type": "string", "description": "Text to transform to uppercase", "required": true } }When to Use This Pattern
Simple data transformations (uppercase, lowercase, formatting)
Calculations that don't require external data
Data validation or sanitization
Format conversions
Improvements You Could Add
Input validation (check that text exists and is a string)
Error handling (wrap in try-catch)
Additional transformation options (lowercase, title case, etc.)
Example 2: HTTP API Call with Error Handling
This example shows how to make HTTP requests to external APIs, which is one of the most common use cases for MCP tools. It includes proper error handling and secret management.
How It Works
Validates inputs - Checks that required parameters and secrets are present
Makes HTTP request - Uses fetch() to call the external API
Handles HTTP errors - Checks response status and provides specific error messages
Parses response - Converts JSON response to JavaScript object
Extracts relevant data - Pulls out only the data needed, transforming it as necessary
Error handling - Wraps everything in try-catch for unexpected errors
Key Features
URL encoding - Uses encodeURIComponent() to safely include the city name in the URL
Secret access - Gets API key from workspace secrets via config
Specific error messages - Different error messages for different failure scenarios
Data transformation - Extracts and formats only the needed data from the API response
Optional chaining - Uses ?. to safely access nested properties that might not exist
Parameter Schema
Required Workspace Secret
This tool requires a workspace secret named OPENWEATHER_API_KEY containing your OpenWeatherMap API key.
When to Use This Pattern
Fetching data from REST APIs
Integrating with external services
Retrieving real-time information
Any tool that needs to access external data
Example 3: Data Processing and Calculations
This example demonstrates how to process arrays of data and perform calculations. It shows common data processing patterns you'll use in many tools.
How It Works
Validates array input - Ensures the parameter is an array and not empty
Validates array contents - Checks that all elements are valid numbers
Performs calculations - Uses JavaScript array methods and Math functions
Calculates multiple statistics - Sum, average, min, max, and median
Formats results - Rounds decimal values for readability
Key Features
Array validation - Comprehensive validation ensures data quality
Array methods - Uses reduce(), every(), and sort() for data processing
Spread operator - Uses [...numbers] to create a copy before sorting (doesn't mutate original)
Median calculation - Shows how to calculate more complex statistics
Rounding - Formats numbers for better readability
Parameter Schema
When to Use This Pattern
Statistical calculations
Data aggregation
Array processing and transformation
Mathematical operations on datasets
Example 4: Parameter Validation and Data Processing
This example shows comprehensive parameter validation and how to handle optional parameters with defaults. It demonstrates best practices for working with user input.
How It Works
Extracts parameters - Uses destructuring to get all parameters at once
Validates required parameters - Checks that name and email exist and are the correct type
Validates formats - Uses regex to validate email format
Validates optional parameters - If age is provided, validates it's a reasonable number
Normalizes data - Trims whitespace, converts email to lowercase, rounds age
Returns processed data - Returns the cleaned and validated data
Key Features
Comprehensive validation - Validates type, format, and business rules
Clear error messages - Each validation failure has a specific error message
Data normalization - Cleans and standardizes input data
Optional parameter handling - Shows how to handle optional parameters with defaults
Type checking - Explicitly checks types to prevent errors
Parameter Schema
When to Use This Pattern
User input processing
Data validation and sanitization
Form processing
Any tool that accepts user-provided data
Example 5: Using Workspace Secrets
This example demonstrates how to securely access and use workspace secrets. It shows the proper pattern for API authentication and configuration management.
How It Works
Accesses secrets - Gets API key and base URL from workspace secrets
Validates secrets exist - Checks that required secrets are configured
Validates secret format - Validates that the API URL is a valid URL
Uses secrets securely - Includes API key in request headers
Makes authenticated request - Uses the secrets to authenticate with the API
Key Features
Secret validation - Checks that secrets exist before using them
Helpful error messages - Tells users exactly what secrets are missing
URL validation - Validates that URLs are properly formatted
Secure usage - Never logs or exposes secrets in error messages
Flexible configuration - Allows API URL to be configured via secrets
Required Workspace Secrets
MY_API_KEY- The API key for authenticationAPI_BASE_URL- The base URL for the API (e.g., "https://api.example.com")
When to Use This Pattern
Any tool that needs to authenticate with external APIs
Tools that need configuration values
Tools that connect to databases or services
Any tool that uses sensitive credentials
Security Best Practices
Never hardcode secrets - Always use workspace secrets
Validate secrets exist - Check before using to provide clear error messages
Don't log secrets - Never use console.log with secret values
Don't expose in errors - Error messages should never include secret values
Use descriptive secret names - Name secrets clearly so it's obvious what they're for
Example 6: Complete Tool with All Best Practices
This example combines all the patterns above into a complete, production-ready tool that demonstrates best practices for error handling, validation, API calls, and data processing.
What This Example Demonstrates
Comprehensive validation - Validates all inputs thoroughly
Secret management - Properly accesses and validates secrets
URL construction - Safely builds URLs with encoding
HTTP error handling - Handles different HTTP status codes specifically
Data processing - Transforms and formats API response data
Conditional logic - Includes optional data based on parameters
Error logging - Logs errors for debugging without exposing secrets
Structured returns - Returns consistent, well-formatted data
Parameter Schema
This example represents a production-ready tool that you can use as a template for building your own tools. It demonstrates all the patterns and best practices discussed throughout this documentation.
Summary: Key Patterns to Remember
Always validate inputs - Check that required parameters exist and are the correct type
Check for secrets - Validate that required secrets exist before using them
Handle errors gracefully - Use try-catch and provide clear error messages
Use async/await - Makes asynchronous code readable and maintainable
Return structured data - Always return { success, data } or { success, error }
Encode URLs safely - Use encodeURIComponent() for URL parameters
Never expose secrets - Don't log or include secrets in error messages
Process data consistently - Transform and format data before returning it
Following these patterns will help you create reliable, maintainable tools that work well with AI assistants and provide a good user experience.
Last updated