mcp-ts-core Framework

repository·main·Indexed 40 days ago

https://github.com/cyanheads/mcp-ts-core

An agent-native TypeScript framework for building Model Context Protocol (MCP) servers. Version 0.13.6 provides runtime infrastructure—including auth, storage, logging, and deployment—and 'Agent Skills' to help AI agents build, test, and ship their own tools and services.

Tokens
331.1K
Snippets
725
Records
1.3K
Agent score
99%

What's inside mcp-ts-core

  1. Overview of Parsing Utilities (`utils/parsing`)

    main

    The @cyanheads/mcp-ts-core/utils module provides a suite of Tier 3 parsers for common data formats. These parsers are lazy-loaded on first call to minimize initial bundle size.

    Common Behaviors

    • Async by default: All methods are async unless explicitly noted as synchronous.
    • Automatic <think> stripping: Parsers automatically strip <think>...</think> blocks from the start of input and log them at debug level (except dateParser and pdfParser).
    • Optional Context: The context? parameter is optional and accepts either a Context handler or a RequestContext bag.
    • Input Budgets: Parsers are unbounded by default. To prevent memory issues, pass maxBytes to reject inputs exceeding the limit. This throws a ValidationError with reason: 'parser_input_too_large'. Use DEFAULT_TEXT_PARSER_MAX_BYTES (1 MiB) or DEFAULT_BINARY_PARSER_MAX_BYTES (25 MiB) as reference values.
    • Error Handling: Errors throw McpError. The error message follows the pattern <summary>: <library message>. The data field contains { reason }, while the original stack and input sample are preserved on the cause property.
    import { yamlParser, xmlParser, csvParser, jsonParser, pdfParser, dateParser, frontmatterParser } from '@cyanheads/mcp-ts-core/utils';
  2. Overview of the Model Context Protocol (MCP)

    main

    The Model Context Protocol (MCP) is an open protocol designed to standardize the integration between LLM applications (Hosts) and external data sources or tools (Servers). It uses JSON-RPC 2.0 messages to facilitate communication.

    Core Participants

    • Hosts: LLM applications that initiate connections (e.g., an AI-powered IDE or chat interface).
    • Clients: Connectors residing within the host application that manage the connection to servers.
    • Servers: Services that provide specific context, data, or capabilities to the client/host.

    This protocol is inspired by the Language Server Protocol (LSP), aiming to provide a consistent way to add context and tools to the AI ecosystem.

  3. Overview of MCP Authorization Extensions

    main

    The Model Context Protocol (MCP) provides supplementary authorization mechanisms via the ext-auth extensions to handle scenarios where the standard OAuth 2.0 interactive user consent flow is insufficient. While the core MCP specification handles interactive user-to-server authorization, these extensions address machine-to-machine (M2M) and enterprise-scale requirements.

    Key Use Cases

    • Machine-to-Machine (M2M): Background services, CI/CD pipelines, and automated workflows that require authentication without human intervention.
    • Enterprise Environments: Centralized identity management where access is controlled via an organization's Identity Provider (IdP) rather than individual user consent.
  4. Overview of Model Context Protocol (MCP) components

    main

    The Model Context Protocol is a modular system designed to enable rich interactions between clients and servers. It is composed of several layers:

    • Base Protocol: Core JSON-RPC message types.
    • Versioning and Compatibility: Mechanisms for protocol version and extension negotiation.
    • Message Patterns: Supported patterns like request/response, multi-round-trip requests (MRTR), and subscribe/notify.
    • Authorization: An authentication and authorization framework (primarily for HTTP-based transports).
    • Server Features: Capabilities exposed by servers, such as Resources, Prompts, and Tools.
    • Client Features: Capabilities provided by clients, such as Elicitation, Sampling, and Root directory lists.
    • Utilities: Cross-cutting concerns like logging and argument completion.

    All implementations MUST support the base protocol, versioning, and the core message patterns.

  5. Overview of @cyanheads/mcp-ts-core/utils

    main

    The @cyanheads/mcp-ts-core/utils package provides a collection of helper utilities for common tasks in MCP server development.

    Key Usage Rules

    • Tier 3 Dependencies: Some utilities have optional peer dependencies (labeled as Tier 3). You must install these manually (e.g., bun add js-yaml) to use the corresponding methods.
    • Async Lazy-Loading: All Tier 3 methods are async. They will attempt to lazy-load the required dependency upon the first call.
    • Context Handling: When using helpers that require a context parameter, you can pass either a Context handler or a RequestContext bag. You should pass the ctx object through directly without slicing it.
  6. Understand the Model Context Protocol (MCP) Schema Structure

    main

    The Model Context Protocol (MCP) uses a JSON-RPC based schema to facilitate communication between clients and servers. The schema is organized into several functional areas:

    • Base Protocol: Defines the core JSON-RPC messaging patterns, including requests, responses, notifications, and error handling.
    • Client Features: Capabilities provided by the client, such as roots (managing file system access), sampling (allowing servers to request completions from the LLM), and elicitation (requesting user input).
    • Server Features: Capabilities provided by the server, including prompts (pre-defined prompt templates), resources (read-only data access), and tools (executable functions).
    • Common Types: Shared data structures like Content (text, images, audio), Error, and LoggingLevel used across all features.
  7. Use the Code Simplifier workflow

    main

    The code-simplifier is a workflow designed to perform a cleanup pass over a session's changes or a specific target (a named path or the whole codebase). It analyzes git diff or the specified target to simplify, consolidate, and align code with the existing codebase.

    Key capabilities:

    • Modernizes syntax.
    • Removes unnecessary complexity.
    • Consolidates duplicated logic.
    • Catches efficiency issues.
    • Aligns code with existing codebase patterns (prioritizing cohesion over local perfection).

    When to use it:

    • After a substantive working session.
    • When explicitly asked to: clean up, simplify, reduce slop, consolidate, modernize, tighten up, de-slop, or scan a codebase.
    • For @cyanheads/mcp-ts-core projects, it includes specialized transformations for tool/resource/prompt definitions, the ctx pattern, error factories, and framework idioms.
  8. What is the Model Context Protocol (MCP)?

    main

    The Model Context Protocol (MCP) is an open protocol designed to standardize the integration between LLM applications (Hosts) and external data sources or tools (Servers). It allows developers to build composable integrations that provide language models with necessary context and execution capabilities.

    MCP uses JSON-RPC 2.0 messages for communication and follows a architecture similar to the Language Server Protocol (LSP), standardizing how tools and context are added to the AI ecosystem.

  9. What is DataCanvas and when to use it

    main

    Overview

    DataCanvas is a Tier 3 analytical workspace for tabular MCP servers, backed by DuckDB. While IStorageProvider is for key/value blob storage, DataCanvas provides an analytical surface to register tabular data from upstream APIs, run SQL queries across multiple tables, and export results (CSV, Parquet, or JSON).

    When to use DataCanvas

    Use DataCanvas only when both of the following conditions are met:

    1. The data is analytical, not just large: The data should be suitable for SQL operations like SELECT ... GROUP BY, joins, or time-series filtering. If the workflow is simply finding a record via metadata (titles, IDs), use standard MCP list filtering instead. The decision is based on shape, not just row count.
    2. The data is too big to inline: If a result set is small (e.g., $\le \sim 100$ rows of compact data), inline it in the tool response. Use DataCanvas as the third option for larger, complex tabular datasets.

    Critical Requirement

    If a tool emits a canvas_id, that server must also provide a dataframe_query tool. Without a query tool, the canvas_id is unusable by an agent.

  10. Overview of MCP Authorization Extensions

    main

    The MCP protocol supports several authorization extensions that allow for additional mechanisms beyond the core protocol. These extensions follow these characteristics:

    • Optional: Implementations can choose whether or not to adopt them.
    • Additive: They add new capabilities without breaking core protocol functionality.
    • Composable: They are modular and can be used together without conflicts.
    • Versioned independently: They follow the core MCP versioning cycle but can have their own independent versions.

    A list of supported extensions is maintained in the MCP Authorization Extensions repository.

  11. Overview of Streamable HTTP Transport

    main

    Streamable HTTP is an MCP transport where the server operates as an independent process handling multiple client connections via a single HTTP endpoint (the MCP endpoint) that accepts POST requests.

    Key characteristics:

    • Request Model: Every JSON-RPC request or notification from the client is sent as its own individual HTTP POST.
    • Response Model: The server responds to each request with either a single JSON object (application/json) or a Server-Sent Events (SSE) stream (text/event-stream) scoped specifically to that request.
    • Notifications: Request-scoped notifications (like progress) are sent via the SSE response stream. Long-lived change notifications (like resource updates) are delivered via a dedicated long-lived stream obtained through a subscriptions/listen request.
    • Server-to-Client Interactions: Interactions like sampling or elicitation use the Multi Round-Trip Requests (MRTR) pattern, where the server returns an InputRequiredResult containing input requests, and the client retries the original request with the necessary inputResponses.
  12. JSON Schema usage and dialects in MCP

    main

    MCP uses JSON Schema for validation. Implementations must adhere to the following dialect rules:

    1. Default Dialect: If a schema does not include a $schema field, it defaults to JSON Schema 2020-12. Clients and servers MUST support this.
    2. Explicit Dialect: Schemas MAY include a $schema field to specify a different dialect (e.g., draft-07).
    3. Validation Requirements:
      • Implementations MUST validate schemas according to their declared or default dialect.
      • Implementations MUST handle unsupported dialects gracefully by returning an error indicating the dialect is not supported.
      • Implementations SHOULD document which additional dialects they support.
    #### Default dialect (2020-12):
    ```json
    {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "age": { "type": "integer", "minimum": 0 }
      },
      "required": ["name"]
    }

    Explicit dialect (draft-07):

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "age": { "type": "integer", "minimum": 0 }
      },
      "required": ["name"]
    }