npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@the-ihor/mcp-sdk-typescript

v1.1.0

Published

Production-ready MCP SDK for TypeScript with automatic Bun optimization, streamable HTTP transport, and real-time session management

Readme

MCP SDK for TypeScript

MCP SDK for TypeScript

Production-ready Model Context Protocol (MCP) SDK for TypeScript with automatic runtime optimization (Bun/Node.js), advanced streamable HTTP transport, comprehensive error handling, and enterprise-grade session management.

✨ Features

  • 🚀 Runtime Optimized: Automatically detects and optimizes for Bun or Node.js
  • High Performance: Uses Bun.serve when available, graceful Node.js fallback
  • 🔄 Real-Time Communication: Streamable HTTP transport with Server-Sent Events (SSE)
  • 🛡️ Type Safety: Full TypeScript support with Zod schema validation
  • 📡 Session Management: Advanced request-response correlation and session tracking
  • 🔧 Generator-Based Tools: Async generator pattern for streaming responses
  • 🛠️ Production Ready: Comprehensive error handling and memory management
  • 📚 Well Documented: Enterprise-grade JSDoc documentation
  • 🎯 MCP Compliant: Full support for MCP 2025-03-26 specification
  • 🔌 Universal Compatibility: Works seamlessly in both Bun and Node.js environments

🚀 Installation

# Using Bun (recommended for performance)
bun add @the-ihor/mcp-sdk-typescript

# Using npm/Node.js
npm install @the-ihor/mcp-sdk-typescript

# Using yarn
yarn add @the-ihor/mcp-sdk-typescript

📖 Quick Start

import { MCPApp, TextResponse, ProgressResponse, LogResponse, z } from "@the-ihor/mcp-sdk-typescript";

const app = new MCPApp({
  name: "my-mcp-server",
  version: "1.0.0",
  transport: {
    host: "localhost",
    port: 3000,
    path: "/mcp"
  }
});

// Create tools with streaming responses
app
  .createTool({
    name: "process-data",
    description: "Process data with real-time progress updates",
    schema: z.object({
      data: z.array(z.string()).describe("Data items to process"),
      delay: z.number().optional().default(100).describe("Processing delay in ms")
    }),
    handler: async function* (args) {
      yield new LogResponse("Starting data processing", "info");
      
      for (let i = 0; i < args.data.length; i++) {
        yield new ProgressResponse(`Processing item ${i + 1}`, i + 1, args.data.length);
        
        // Simulate processing
        await new Promise(resolve => setTimeout(resolve, args.delay));
        
        yield new TextResponse(`Processed: ${args.data[i]}`);
      }
      
      yield new LogResponse("Processing completed", "info");
    }
  })
  .createTool({
    name: "echo",
    description: "Echo back input with optional transformations",
    schema: z.object({
      text: z.string().describe("Text to echo"),
      uppercase: z.boolean().optional().describe("Convert to uppercase"),
      repeat: z.number().min(1).max(10).optional().default(1).describe("Number of repetitions")
    }),
    handler: async function* (args) {
      let result = args.uppercase ? args.text.toUpperCase() : args.text;
      
      for (let i = 0; i < args.repeat; i++) {
        yield new TextResponse(`Echo ${i + 1}: ${result}`);
      }
    }
  });

// Start the server
await app.start();
console.log("🎯 MCP Server running and ready for connections!");

🏗️ Architecture

Core Components

MCPApp

Main application class providing:

  • Type-safe tool registration with automatic validation
  • Server lifecycle management
  • Built-in error handling and logging

StreamableHttpTransport

Advanced HTTP transport featuring:

  • Runtime Detection: Automatically uses optimal server implementation
  • Bun Optimization: Uses Bun.serve for maximum performance when available
  • Node.js Compatibility: Seamless fallback to Node.js HTTP server
  • Session Correlation: Request-response mapping for proper delivery
  • Real-Time Streaming: Server-Sent Events for immediate responses
  • Error Recovery: Comprehensive fallback mechanisms
  • Memory Management: Automatic cleanup of expired requests

Response System

Rich response types for various content:

  • TextResponse: Plain text content
  • ImageResponse: Images with MIME type support
  • ResourceResponse: File and URL references
  • ProgressResponse: Real-time progress updates
  • LogResponse: Structured logging with levels
  • ErrorResponse: Typed error information
  • RawResponse: Custom content types

🔧 Advanced Usage

Error Handling

const transport = new StreamableHttpTransport({
  host: "localhost",
  port: 3000,
  path: "/mcp"
});

// Handle transport-level errors
transport.onError((error) => {
  console.error("Transport error:", error.message);
  // Error context: "Server startup failed: ..." 
  // Error context: "Failed to parse JSON-RPC message: ..."
});

// Handle application errors
app.createTool({
  name: "risky-operation",
  schema: z.object({ value: z.number() }),
  handler: async function* (args) {
    try {
      if (args.value < 0) {
        yield new ErrorResponse("Negative values not allowed", "INVALID_INPUT");
        return;
      }
      yield new TextResponse(`Result: ${Math.sqrt(args.value)}`);
    } catch (error) {
      yield new ErrorResponse(`Unexpected error: ${error.message}`, "INTERNAL_ERROR");
    }
  }
});

Session Management

The transport automatically handles session correlation:

// Client establishes SSE connection: GET /mcp
// Server returns X-Session-ID header
// Client sends requests with session ID: POST /mcp + X-Session-ID header
// Server routes responses back to correct client via SSE stream

🛠️ Development

Using Bun (Recommended)

# Install dependencies
bun install

# Build the library
bun run build

# Type checking
bun run typecheck

# Linting
bun run lint
bun run lint:fix

# Run tests
bun test

Using Node.js

# Install dependencies
npm install

# Build the library (requires Bun for build process)
npm run build

# Type checking
npm run typecheck

# Linting
npm run lint

# Run tests
npm test

Runtime Detection

The SDK automatically detects your runtime:

// Will use Bun.serve if running in Bun
// Will use Node.js HTTP server if running in Node.js
const app = new MCPApp({ name: 'my-app', version: '1.0.0' });
await app.start(); // Optimized for your runtime!

📁 Project Structure

mcp-sdk-typescript/
├── src/
│   ├── app.ts          # Main MCPApp class
│   ├── transport.ts    # HTTP transport with runtime detection
│   ├── responses.ts    # Response type definitions
│   ├── schemas.ts      # Schema utilities and validation
│   └── index.ts        # Public API exports
├── dist/               # Build output
├── docs/               # Additional documentation
└── tests/              # Test suites

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make changes and add tests
  4. Ensure linting passes: bun run lint
  5. Commit changes: git commit -m "✨ feat: Add amazing feature"
  6. Push to branch: git push origin feature/amazing-feature
  7. Open a Pull Request

📄 License

MIT License - see LICENSE file for details.

🔗 Links


Built with ❤️ by The Ihor using Bun, TypeScript, and Claude