@reaatech/mcp-contract-core
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
npm install @reaatech/mcp-contract-core
pnpm add @reaatech/mcp-contract-core
Feature Overview
Enums — Severity, TestCategory, and TestSuite for categorizing test results
Result types — TestResult, TestReport, and ValidationError interfaces for structured test output
Validator contracts — Validator and ValidationContext interfaces for implementing custom validators
MCP client types — MCPClient, 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
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
Export Kind Description Severityenum CRITICAL, WARNING, INFO — severity levels for test resultsTestCategoryenum REGISTRY, PROTOCOL, ROUTING, SECURITY, PERFORMANCE — validator categoriesTestSuiteenum REGISTRY, PROTOCOL, ROUTING, SECURITY, PERFORMANCE, ALL — test suite identifiers
Results
Export Kind Description TestResultinterface Individual test result with validator, category, passed, severity, message, remediation, details, duration, timestamp TestReportinterface Aggregated test report with id, endpoint, timing, results array, summary, failures, passed flag, error, version ValidationErrorinterface Validation error with field, message, line, severity, type
Validation
Export Kind Description Validatorinterface Validator contract with name, category, severity, validate(), and optional setup()/teardown() ValidationContextinterface Context passed to validators with client, endpoint, options, requestId, artifacts
Client Types
Export Kind Description MCPClientinterface MCP client interface with connect(), sendRequest(), callTool(), listTools(), disconnect(), getSessionId() MCPRequestinterface JSON-RPC 2.0 request with jsonrpc, method, id, params MCPResponse<T>interface JSON-RPC 2.0 response with jsonrpc, id, optional result or error MCPErrorinterface JSON-RPC 2.0 error with code, message, data ToolDefinitioninterface MCP tool definition with name, description, inputSchema ToolResultinterface Tool call result with content array and optional isError
Config Types
Export Kind Description TestOptionsinterface Test execution options with timeout, retries, failOn, verbose, suites, yamlPath
Schemas
Export Kind Description AgentConfigSchemaZodObject Validates agent YAML definition (agent_id, display_name, description, endpoint, type, is_default, confidence_threshold, clarification_required, examples) MCPRequestSchemaZodObject Validates JSON-RPC 2.0 request structure MCPErrorSchemaZodObject Validates JSON-RPC 2.0 error structure MCPResponseSchemaZodObject Validates JSON-RPC 2.0 response (enforces exactly one of result or error) ToolDefinitionSchemaZodObject Validates MCP tool definition (name, description, inputSchema) AgentRequestContractSchemaZodObject Validates orchestrator-to-agent request contract AgentResponseContractSchemaZodObject Validates agent-to-orchestrator response contract
Schema Types
Export Kind Description AgentConfigInputtype Inferred type from AgentConfigSchema AgentConfigtype Alias for AgentConfigInput AgentTypetype String literal type mcp ToolDefinitionInputtype Inferred type from ToolDefinitionSchema AgentRequestContracttype Inferred type from AgentRequestContractSchema AgentResponseContracttype Inferred type from AgentResponseContractSchema
Utilities
Export Kind Description generateId()function Generate a unique request ID using timestamp and random string generateUUID()function Generate a cryptographically random UUID v4 sleep(ms)function Promise-based sleep for a given number of milliseconds retry(fn, opts)function Retry a function with exponential backoff measureTime(fn)function Measure execution time of an async function, returns { result, durationMs } now()function Get current ISO 8601 timestamp string truncate(str, maxLength)function Truncate a string to a maximum length, appending ... if truncated redactSensitiveData(obj, keys?)function Redact sensitive keys (password, token, secret, key, authorization) from an object percentile(values, p)function Calculate the p-th percentile from an array of numbers isValidURL(value)function Check if a value is a valid http/https URL isPrivateURL(value)function Check if a URL is private/localhost (SSRF protection) calculateStats(values)function Calculate min, max, mean, p50, p90, p99 from an array of values isValidUUID(value)function Validate a string against UUID v4 format getVersion()function Read 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:
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;
}
Related Packages
License
MIT