Introduction

Welcome to Chapter 3! In our previous discussions, we explored the fundamental concepts of the Model Context Protocol (MCP), understanding its purpose as an open standard for AI agents to discover and interact with external tools. We learned what MCP is and why it’s so crucial for building intelligent, capable agents. Now, it’s time to roll up our sleeves and get practical!

This chapter is all about setting up your local development environment to start building with MCP. Specifically, we’ll focus on getting the TypeScript SDK v2 ready, as it’s a powerful and popular choice for many developers. By the end of this chapter, you’ll have a fully configured workspace, ready to define your first MCP tool and integrate it into an agent workflow. Think of this as laying the groundwork – a crucial step before you start building your dream AI-powered applications.

Before we dive in, ensure you have a basic understanding of Node.js, npm (or Yarn), and TypeScript. If those terms sound completely new, a quick refresher on Node.js and TypeScript fundamentals would be beneficial, as we’ll be using them extensively. Ready? Let’s get your MCP workspace set up!

Core Concepts: The MCP TypeScript SDK v2

Before we install anything, let’s understand what we’re about to set up.

What is the MCP TypeScript SDK v2?

The Model Context Protocol TypeScript SDK (Software Development Kit) provides a set of libraries and utilities that simplify interacting with the MCP specification. Instead of manually crafting JSON schemas and handling complex protocol messages, the SDK offers convenient abstractions to:

  • Define Tools: Create structured descriptions of your tools’ capabilities, inputs, and outputs using familiar TypeScript types.
  • Register Tools: Facilitate the process of making your tools discoverable by AI agents.
  • Handle Tool Invocations: Process requests from AI agents to execute your tools.
  • Manage Context: Work with the dynamic context that agents provide when invoking tools.

The v2 designation is important. As of 2026-03-20, the MCP specification itself is still a draft. The TypeScript SDK v2 represents the latest anticipated stable release (Q1 2026), designed to align with the evolving protocol. This means you’re working with the most current best practices and features.

Why TypeScript for MCP Development?

TypeScript offers several compelling advantages for building MCP tools:

  1. Type Safety: MCP tools rely heavily on structured data (JSON Schema). TypeScript’s static typing allows you to define these structures clearly and catch type-related errors before runtime, leading to more robust and reliable tools.
  2. Improved Developer Experience: Features like autocompletion, refactoring support, and immediate feedback from your IDE (like VS Code) make development faster and less error-prone.
  3. Readability and Maintainability: Explicit types make your code easier to understand and maintain, especially in larger projects or when collaborating with a team.
  4. Scalability: For complex MCP tools or systems with many tools, TypeScript helps manage complexity as your project grows.

Key Components of the TypeScript SDK (v2)

The MCP TypeScript SDK is typically composed of a few core packages, each with a specific responsibility:

  • @modelcontextprotocol/sdk-core: This package provides the fundamental building blocks for interacting with the MCP. It might include base classes, utility functions, and core protocol definitions.
  • @modelcontextprotocol/tool-definition: This package focuses specifically on helping you define your tools’ schemas. It will likely offer decorators, helper functions, or classes to describe inputs, outputs, and metadata for your tools in a type-safe manner.
  • Other potential packages: Depending on the SDK’s design, there might be separate packages for server implementations, client-side interactions, or specific integration patterns. For now, we’ll focus on the core and tool definition.

Think of it like building with LEGOs: the sdk-core provides the basic bricks, and tool-definition gives you specialized pieces for building a specific part of your structure – the tool description itself.

Step-by-Step Implementation: Setting Up Your Environment

Let’s get your hands dirty! We’ll set up a new TypeScript project and install the necessary MCP SDK packages.

Step 1: Verify Prerequisites

First, let’s ensure you have Node.js and npm (or Yarn) installed, along with TypeScript.

Check Node.js and npm

Open your terminal or command prompt and run these commands:

node -v
npm -v

What to Observe: You should see version numbers for Node.js and npm. As of 2026-03-20, a recent LTS (Long Term Support) version of Node.js (e.g., Node.js 20.x or 22.x) and a corresponding npm version (e.g., 10.x or 11.x) are recommended. If you don’t have them or your versions are very old, please install or update them. You can find installers and instructions on the official Node.js website.

Check TypeScript

Next, check your TypeScript installation:

tsc -v

What to Observe: You should see a TypeScript version number (e.g., Version 5.x.x). If tsc is not found or the version is old, you can install or update it globally:

npm install -g typescript

This ensures the TypeScript compiler is available system-wide.

Step 2: Initialize a New TypeScript Project

Now, let’s create a new directory for our MCP project and initialize it.

  1. Create Project Directory: Choose a location for your project and create a new folder. Let’s call it my-first-mcp-tool.

    mkdir my-first-mcp-tool
    cd my-first-mcp-tool
    
  2. Initialize npm Project: Inside your new directory, initialize a new Node.js project. This creates a package.json file to manage your project’s dependencies.

    npm init -y
    

    What to Observe: You’ll see a package.json file created. The -y flag answers “yes” to all prompts, creating a default configuration. You can always edit this file later.

  3. Initialize TypeScript Configuration: Next, we’ll initialize TypeScript for our project. This creates a tsconfig.json file, which tells the TypeScript compiler how to compile your .ts files into .js.

    tsc --init
    

    What to Observe: A tsconfig.json file will appear in your project root. This file contains many configuration options. For now, we’ll keep most defaults, but we’ll uncomment a few important ones.

    Open tsconfig.json and ensure these lines are uncommented and set as follows:

    // tsconfig.json
    {
      "compilerOptions": {
        "target": "es2022", // Or "esnext" for the latest features
        "module": "commonjs", // Or "esnext" if using ESM
        "rootDir": "./src", // Source files will be in a 'src' folder
        "outDir": "./dist", // Compiled JavaScript will go here
        "esModuleInterop": true, // Recommended for better module interoperability
        "forceConsistentCasingInFileNames": true, // Good practice
        "strict": true, // Enable all strict type-checking options (highly recommended!)
        "skipLibCheck": true // Skip type checking of all declaration files (*.d.ts)
      },
      "include": ["src/**/*"] // Tell TypeScript to include files in 'src'
    }
    

    Why these settings?

    • target: Specifies the JavaScript version your code will be compiled to. es2022 (or esnext) ensures you can use modern JS features.
    • module: Determines the module system for the generated JavaScript. commonjs is standard for Node.js, while esnext (or nodenext) is for ECMAScript Modules (ESM). We’ll stick with commonjs for simplicity here.
    • rootDir and outDir: Organize your source (.ts) and compiled (.js) files.
    • esModuleInterop: Helps with importing CommonJS modules into ES modules (and vice versa) more smoothly.
    • strict: Enables a broad range of type-checking rules. This is crucial for robust TypeScript development.
    • skipLibCheck: Speeds up compilation by skipping type checks on declaration files in node_modules.

Step 3: Install the MCP TypeScript SDK

Now for the main event! We’ll install the MCP TypeScript SDK packages. Remember, the SDK is actively evolving. We’ll specify a version that aligns with the anticipated v2 stable release (Q1 2026). For this guide, let’s use 2.0.0-beta.1 as a placeholder for the initial v2 release, acknowledging its draft nature as of 2026-01-26.

npm install @modelcontextprotocol/sdk-core@2.0.0-beta.1 @modelcontextprotocol/tool-definition@2.0.0-beta.1

What to Observe: npm will download and install these packages and their dependencies. Your package.json file will be updated with these new entries under dependencies. You’ll also see a node_modules directory created, containing all the installed libraries.

Step 4: Create Your First Basic MCP Tool Definition File

Let’s create a simple TypeScript file to verify our setup and get a feel for defining a tool.

  1. Create a src directory: As per our tsconfig.json, our source files will live in a src folder.

    mkdir src
    
  2. Create index.ts: Inside src, create a file named index.ts.

    touch src/index.ts
    
  3. Add Tool Definition Code: Open src/index.ts and add the following code:

    // src/index.ts
    import { ToolDefinition, JSONSchema } from '@modelcontextprotocol/tool-definition';
    
    /**
     * Defines a simple "Hello World" tool using the MCP TypeScript SDK.
     * This tool takes a 'name' as input and returns a greeting.
     */
    const helloWorldTool: ToolDefinition = {
      // Unique identifier for the tool.
      // Conventionally, this should be a URL or URN that uniquely identifies your tool globally.
      // For local development, a simple string is fine.
      id: 'https://example.com/tools/helloWorld',
    
      // A human-readable name for the tool.
      name: 'helloWorld',
    
      // A brief description that helps AI agents understand what the tool does.
      description: 'Greets a person by their name.',
    
      // Defines the input parameters the tool expects, using JSON Schema.
      input_schema: {
        type: 'object',
        properties: {
          name: {
            type: 'string',
            description: 'The name of the person to greet.',
          },
        },
        required: ['name'], // 'name' is a mandatory input.
      } as JSONSchema, // Type assertion for clarity and strictness
    
      // Defines the output structure the tool will return.
      output_schema: {
        type: 'object',
        properties: {
          greeting: {
            type: 'string',
            description: 'The greeting message.',
          },
        },
        required: ['greeting'],
      } as JSONSchema,
    
      // UI resources can be declared here for tools that have a visual component.
      // For this simple example, we'll leave it empty.
      ui_resources: [],
    };
    
    // For now, we'll just log the tool definition to verify it's correctly structured.
    console.log('MCP Tool Definition created successfully:');
    console.log(JSON.stringify(helloWorldTool, null, 2));
    
    // In a real application, you would then register this tool with an MCP server
    // or integrate it with an AI agent framework.
    

    Explanation of the code:

    • import { ToolDefinition, JSONSchema } from '@modelcontextprotocol/tool-definition';: We import the necessary types from the SDK. ToolDefinition is the main interface for describing a tool, and JSONSchema helps us define the structure of inputs and outputs.
    • id: A unique identifier. In a real-world scenario, this would be a resolvable URL or URN.
    • name: A short, descriptive name for the tool.
    • description: A more detailed explanation for AI agents to understand the tool’s purpose. This is crucial for agent reasoning!
    • input_schema: This is where we define the shape of the data our tool expects as input. We use a standard JSON Schema object. Here, it expects an object with a name property, which must be a string.
    • output_schema: Similar to input_schema, this defines the shape of the data our tool will return. In this case, an object with a greeting property, also a string.
    • ui_resources: This is an advanced feature (mentioned in the ext-apps repo) that allows tools to declare UI components. We’ll explore this in later chapters, but it’s good to know it’s part of the ToolDefinition.
    • console.log: We’re simply printing the defined tool object to the console to confirm that TypeScript correctly processed it and that the SDK types are working.

Step 5: Compile and Run Your Code

Finally, let’s compile our TypeScript code into JavaScript and run it.

  1. Compile TypeScript:

    npx tsc
    

    What to Observe: If everything is set up correctly, you should see no errors! A new dist directory will be created, and inside it, index.js (the compiled JavaScript version of your src/index.ts file).

  2. Run the Compiled JavaScript:

    node dist/index.js
    

    What to Observe: You should see the JSON representation of your helloWorldTool printed to the console! This confirms that your environment is correctly configured, the SDK packages are installed, and TypeScript is compiling your code as expected.

    MCP Tool Definition created successfully:
    {
      "id": "https://example.com/tools/helloWorld",
      "name": "helloWorld",
      "description": "Greets a person by their name.",
      "input_schema": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "description": "The name of the person to greet."
          }
        },
        "required": [
          "name"
        ]
      },
      "output_schema": {
        "type": "object",
        "properties": {
          "greeting": {
            "type": "string",
            "description": "The greeting message."
          }
        },
        "required": [
          "greeting"
        ]
      },
      "ui_resources": []
    }
    

Congratulations! You’ve successfully set up your MCP development environment with the TypeScript SDK v2 and defined your very first tool. This is a huge step!

Mini-Challenge: Extend Your Tool Definition

Now that you’ve got the basics down, let’s try a small modification to solidify your understanding.

Challenge: Modify the helloWorldTool in src/index.ts to accept an optional language parameter. If language is provided (e.g., “es” for Spanish), the tool should indicate that the greeting will be in that language. Update both the input_schema and the description accordingly.

Hint: In JSON Schema, to make a property optional, simply omit it from the required array. Also, remember to update the description field of the tool itself to reflect this new capability.

What to Observe/Learn: After making your changes, re-compile (npx tsc) and re-run (node dist/index.js). Observe the updated JSON output. Notice how TypeScript’s type checking helps you ensure your schema definitions are valid. This exercise reinforces how to declare optional parameters and update tool metadata, which is crucial for building flexible tools.

Common Pitfalls & Troubleshooting

Even with clear steps, development environments can sometimes be tricky. Here are a few common issues and how to troubleshoot them:

  1. tsc command not found or npm install errors:

    • Issue: You might see command not found: tsc or errors during npm install.
    • Troubleshooting:
      • For tsc, ensure you’ve installed TypeScript globally (npm install -g typescript).
      • For npm install errors, check your internet connection. Also, ensure you’re in the correct project directory (my-first-mcp-tool). Sometimes, clearing the npm cache (npm cache clean --force) and retrying the install helps.
  2. TypeScript compilation errors (e.g., “Property ‘x’ does not exist on type ‘y’”):

    • Issue: When running npx tsc, you get type errors.
    • Troubleshooting: This often means your code doesn’t match the types defined by the SDK.
      • Double-check your input_schema and output_schema against the ToolDefinition interface. Are all required properties present? Are the types (e.g., type: 'string') correct?
      • Ensure you have the correct SDK packages and versions installed.
      • Verify your tsconfig.json settings, especially strict: true. While strict is good practice, it can sometimes be overwhelming initially. If you’re stuck, temporarily set strict: false to see if it’s a strictness issue, but always aim to fix the underlying type problem.
  3. node dist/index.js fails with “Cannot find module”:

    • Issue: After compiling, running the JavaScript file throws an error that it can’t find a module.
    • Troubleshooting:
      • Ensure your module setting in tsconfig.json (e.g., commonjs) matches how Node.js expects to load modules. If you’re using type: "module" in your package.json for ESM, then module: "esnext" or nodenext in tsconfig.json would be more appropriate.
      • Verify that npx tsc completed without errors and that dist/index.js actually exists in the dist folder.
      • Make sure you are in the root of your project directory (my-first-mcp-tool) when running node dist/index.js.

Remember, the official Model Context Protocol GitHub repositories are excellent resources for the latest SDK documentation and examples.

Summary

Phew! You’ve accomplished a lot in this chapter. Here’s a quick recap of what we covered:

  • Understanding the MCP TypeScript SDK v2: We grasped its purpose, the benefits of using TypeScript, and its core components.
  • Environment Setup: You successfully installed Node.js, npm/Yarn, and TypeScript.
  • Project Initialization: You created a new TypeScript project with a properly configured package.json and tsconfig.json.
  • SDK Installation: You installed the @modelcontextprotocol/sdk-core and @modelcontextprotocol/tool-definition packages.
  • First Tool Definition: You wrote your first ToolDefinition in TypeScript, demonstrating how to declare tool capabilities, inputs, and outputs using JSON Schema.
  • Compilation and Execution: You compiled your TypeScript code and ran the generated JavaScript, verifying your setup.
  • Mini-Challenge: You practiced extending a tool’s schema, enhancing your understanding of input_schema and description.
  • Troubleshooting: We looked at common issues and how to resolve them.

You now have a solid foundation for building sophisticated AI agent tools! Your development environment is primed and ready.

What’s Next?

In the next chapter, we’ll dive deeper into defining more complex MCP tool schemas. We’ll explore different JSON Schema types, advanced properties, and how to structure your tool definitions for maximum clarity and agent utility. Get ready to design tools that truly empower AI agents!


References


This page is AI-assisted and reviewed. It references official documentation and recognized resources where relevant.