Skip to content
reaatechREAATECH

@reaatech/mcp-contract-core

pending npm

Provides foundational TypeScript interfaces, Zod schemas, and JSON-RPC 2.0 types for validating and interacting with Model Context Protocol (MCP) contracts. It serves as the shared dependency for building custom MCP validators, test suites, and client implementations.

@reaatech/mcp-contract-core

npm version License: MIT CI

Status: Pre-1.0 — APIs may change in minor versions. Pin to a specific version in production.

Core domain types, JSON-RPC 2.0 schemas, and shared utilities for MCP contract validation. Provides the foundational enums, interfaces, Zod schemas, and helper functions used across all @reaatech/mcp-contract-* packages.

Installation

terminal
npm install @reaatech/mcp-contract-core
terminal
pnpm add @reaatech/mcp-contract-core

Feature Overview

  • EnumsSeverity, TestCategory, and TestSuite for categorizing test results
  • Result typesTestResult, TestReport, and ValidationError interfaces for structured test output
  • Validator contractsValidator and ValidationContext interfaces for implementing custom validators
  • MCP client typesMCPClient, MCPRequest, MCPResponse, MCPError, ToolDefinition, ToolResult for JSON-RPC 2.0 interaction
  • Zod schemas — Runtime validation schemas for agent YAML, JSON-RPC messages, tools, and orchestrator contracts
  • Utilities — UUID generation, retry with backoff, URL validation, statistics, sensitive data redaction, and more

Quick Start

ts
import {
  Severity,
  TestCategory,
  TestSuite,
  AgentConfigSchema,
  MCPResponseSchema,
} from '@reaatech/mcp-contract-core';
import type {
  TestResult,
  TestReport,
  Validator,
  AgentConfig,
} from '@reaatech/mcp-contract-core';
 
// Use enums
const severity = Severity.CRITICAL;
const category = TestCategory.PROTOCOL;
 
// Create a test result
const result: TestResult = {
  validator: 'json-rpc-compliance',
  category: TestCategory.PROTOCOL,
  passed: false,
  severity: Severity.CRITICAL,
  message: 'Missing jsonrpc field in response',
  remediation: 'Add "jsonrpc": "2.0" to all responses',
  durationMs: 5,
  timestamp: new Date().toISOString(),
};
 
// Validate with schemas
const parsed = AgentConfigSchema.safeParse({
  agent_id: 'my-agent',
  display_name: 'My Agent',
  description: 'A test agent',
  endpoint: 'https://api.example.com',
  type: 'mcp',
  is_default: false,
  confidence_threshold: 0.8,
  clarification_required: true,
  examples: ['What is the weather?'],
});
 
if (!parsed.success) {
  console.error(parsed.error.flatten());
}

Exports

Categories

ExportKindDescription
SeverityenumCRITICAL, WARNING, INFO — severity levels for test results
TestCategoryenumREGISTRY, PROTOCOL, ROUTING, SECURITY, PERFORMANCE — validator categories
TestSuiteenumREGISTRY, PROTOCOL, ROUTING, SECURITY, PERFORMANCE, ALL — test suite identifiers

Results

ExportKindDescription
TestResultinterfaceIndividual test result with validator, category, passed, severity, message, remediation, details, duration, timestamp
TestReportinterfaceAggregated test report with id, endpoint, timing, results array, summary, failures, passed flag, error, version
ValidationErrorinterfaceValidation error with field, message, line, severity, type

Validation

ExportKindDescription
ValidatorinterfaceValidator contract with name, category, severity, validate(), and optional setup()/teardown()
ValidationContextinterfaceContext passed to validators with client, endpoint, options, requestId, artifacts

Client Types

ExportKindDescription
MCPClientinterfaceMCP client interface with connect(), sendRequest(), callTool(), listTools(), disconnect(), getSessionId()
MCPRequestinterfaceJSON-RPC 2.0 request with jsonrpc, method, id, params
MCPResponse<T>interfaceJSON-RPC 2.0 response with jsonrpc, id, optional result or error
MCPErrorinterfaceJSON-RPC 2.0 error with code, message, data
ToolDefinitioninterfaceMCP tool definition with name, description, inputSchema
ToolResultinterfaceTool call result with content array and optional isError

Config Types

ExportKindDescription
TestOptionsinterfaceTest execution options with timeout, retries, failOn, verbose, suites, yamlPath

Schemas

ExportKindDescription
AgentConfigSchemaZodObjectValidates agent YAML definition (agent_id, display_name, description, endpoint, type, is_default, confidence_threshold, clarification_required, examples)
MCPRequestSchemaZodObjectValidates JSON-RPC 2.0 request structure
MCPErrorSchemaZodObjectValidates JSON-RPC 2.0 error structure
MCPResponseSchemaZodObjectValidates JSON-RPC 2.0 response (enforces exactly one of result or error)
ToolDefinitionSchemaZodObjectValidates MCP tool definition (name, description, inputSchema)
AgentRequestContractSchemaZodObjectValidates orchestrator-to-agent request contract
AgentResponseContractSchemaZodObjectValidates agent-to-orchestrator response contract

Schema Types

ExportKindDescription
AgentConfigInputtypeInferred type from AgentConfigSchema
AgentConfigtypeAlias for AgentConfigInput
AgentTypetypeString literal type mcp
ToolDefinitionInputtypeInferred type from ToolDefinitionSchema
AgentRequestContracttypeInferred type from AgentRequestContractSchema
AgentResponseContracttypeInferred type from AgentResponseContractSchema

Utilities

ExportKindDescription
generateId()functionGenerate a unique request ID using timestamp and random string
generateUUID()functionGenerate a cryptographically random UUID v4
sleep(ms)functionPromise-based sleep for a given number of milliseconds
retry(fn, opts)functionRetry a function with exponential backoff
measureTime(fn)functionMeasure execution time of an async function, returns { result, durationMs }
now()functionGet current ISO 8601 timestamp string
truncate(str, maxLength)functionTruncate a string to a maximum length, appending ... if truncated
redactSensitiveData(obj, keys?)functionRedact sensitive keys (password, token, secret, key, authorization) from an object
percentile(values, p)functionCalculate the p-th percentile from an array of numbers
isValidURL(value)functionCheck if a value is a valid http/https URL
isPrivateURL(value)functionCheck if a URL is private/localhost (SSRF protection)
calculateStats(values)functionCalculate min, max, mean, p50, p90, p99 from an array of values
isValidUUID(value)functionValidate a string against UUID v4 format
getVersion()functionRead the package version from the nearest package.json

Usage Pattern

All Zod schemas are paired with inferred types. Use the schema for runtime validation and the type for compile-time safety:

ts
import { AgentConfigSchema, MCPResponseSchema } from '@reaatech/mcp-contract-core';
import type { AgentConfig, MCPResponse } from '@reaatech/mcp-contract-core';
 
// Runtime validation
function parseAgentConfig(raw: unknown): AgentConfig {
  return AgentConfigSchema.parse(raw);
}
 
// Type annotation
function handleResponse(response: MCPResponse<string>): string | undefined {
  const parsed = MCPResponseSchema.safeParse(response);
  if (!parsed.success) {
    throw new Error('Invalid JSON-RPC response');
  }
  return parsed.data.result;
}

License

MIT