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:
- 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.
- Improved Developer Experience: Features like autocompletion, refactoring support, and immediate feedback from your IDE (like VS Code) make development faster and less error-prone.
- Readability and Maintainability: Explicit types make your code easier to understand and maintain, especially in larger projects or when collaborating with a team.
- 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.
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-toolInitialize npm Project: Inside your new directory, initialize a new Node.js project. This creates a
package.jsonfile to manage your project’s dependencies.npm init -yWhat to Observe: You’ll see a
package.jsonfile created. The-yflag answers “yes” to all prompts, creating a default configuration. You can always edit this file later.Initialize TypeScript Configuration: Next, we’ll initialize TypeScript for our project. This creates a
tsconfig.jsonfile, which tells the TypeScript compiler how to compile your.tsfiles into.js.tsc --initWhat to Observe: A
tsconfig.jsonfile 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.jsonand 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(oresnext) ensures you can use modern JS features.module: Determines the module system for the generated JavaScript.commonjsis standard for Node.js, whileesnext(ornodenext) is for ECMAScript Modules (ESM). We’ll stick withcommonjsfor simplicity here.rootDirandoutDir: 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 innode_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.
Create a
srcdirectory: As per ourtsconfig.json, our source files will live in asrcfolder.mkdir srcCreate
index.ts: Insidesrc, create a file namedindex.ts.touch src/index.tsAdd Tool Definition Code: Open
src/index.tsand 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.ToolDefinitionis the main interface for describing a tool, andJSONSchemahelps 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 anameproperty, which must be a string.output_schema: Similar toinput_schema, this defines the shape of the data our tool will return. In this case, an object with agreetingproperty, also a string.ui_resources: This is an advanced feature (mentioned in theext-appsrepo) that allows tools to declare UI components. We’ll explore this in later chapters, but it’s good to know it’s part of theToolDefinition.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.
Compile TypeScript:
npx tscWhat to Observe: If everything is set up correctly, you should see no errors! A new
distdirectory will be created, and inside it,index.js(the compiled JavaScript version of yoursrc/index.tsfile).Run the Compiled JavaScript:
node dist/index.jsWhat to Observe: You should see the JSON representation of your
helloWorldToolprinted 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:
tsccommand not found ornpm installerrors:- Issue: You might see
command not found: tscor errors duringnpm install. - Troubleshooting:
- For
tsc, ensure you’ve installed TypeScript globally (npm install -g typescript). - For
npm installerrors, 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.
- For
- Issue: You might see
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_schemaandoutput_schemaagainst theToolDefinitioninterface. 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.jsonsettings, especiallystrict: true. Whilestrictis good practice, it can sometimes be overwhelming initially. If you’re stuck, temporarily setstrict: falseto see if it’s a strictness issue, but always aim to fix the underlying type problem.
- Double-check your
- Issue: When running
node dist/index.jsfails with “Cannot find module”:- Issue: After compiling, running the JavaScript file throws an error that it can’t find a module.
- Troubleshooting:
- Ensure your
modulesetting intsconfig.json(e.g.,commonjs) matches how Node.js expects to load modules. If you’re usingtype: "module"in yourpackage.jsonfor ESM, thenmodule: "esnext"ornodenextintsconfig.jsonwould be more appropriate. - Verify that
npx tsccompleted without errors and thatdist/index.jsactually exists in thedistfolder. - Make sure you are in the root of your project directory (
my-first-mcp-tool) when runningnode dist/index.js.
- Ensure your
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.jsonandtsconfig.json. - SDK Installation: You installed the
@modelcontextprotocol/sdk-coreand@modelcontextprotocol/tool-definitionpackages. - First Tool Definition: You wrote your first
ToolDefinitionin 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_schemaanddescription. - 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
- Model Context Protocol - GitHub Organization
- Model Context Protocol Specification and Documentation
- The official TypeScript SDK for Model Context Protocol - GitHub
- JSON Schema Official Website
- Node.js Official Website
- TypeScript Official Website
This page is AI-assisted and reviewed. It references official documentation and recognized resources where relevant.