Skip to content

API Reference

A highly dense reference manual for every public class, function, type, and interface exported by the MCP Fusion framework.


Response Helpers

Because MCP dictates strict return structures, rather than sending complex JSON array trees by hand, use the Fusion helper libraries for instant payload mappings.

success(data)

Creates a success response payload. Auto-detects the input type. If a string is passed, it is used as is. If an object is passed, it is intelligently serialized via JSON.stringify.

typescript
import { success } from '@vinkius-core/mcp-fusion';

return success('Task created');
return success({ id: '1', title: 'My task', status: 'open' });

error(message)

Returns an error response wrapped in a <tool_error> XML envelope with isError: true.

typescript
import { error } from '@vinkius-core/mcp-fusion';

return error('Task not found');
// Output:
// <tool_error>
// <message>Task not found</message>
// </tool_error>

required(field)

Returns a missing-field error with an error code and recovery instruction.

typescript
import { required } from '@vinkius-core/mcp-fusion';

return required('project_id');
// Output:
// <tool_error code="MISSING_REQUIRED_FIELD">
// <message>Required field "project_id" is missing.</message>
// <recovery>Provide the "project_id" parameter and retry.</recovery>
// </tool_error>

toolError(code, options)

Creates a self-healing error response with structured recovery instructions for LLM agents.

typescript
import { toolError } from '@vinkius-core/mcp-fusion';

return toolError('ProjectNotFound', {
    message: `Project '${id}' does not exist.`,
    suggestion: 'Call projects.list to see available IDs.',
    availableActions: ['projects.list'],
});
// Output:
// <tool_error code="ProjectNotFound">
// <message>Project 'xyz' does not exist.</message>
// <recovery>Call projects.list to see available IDs.</recovery>
// <available_actions>projects.list</available_actions>
// </tool_error>

Options:

FieldTypeDescription
messagestringRequired. Human-readable error message.
suggestionstring?Optional. Maps to <recovery> in the XML output.
availableActionsstring[]?Optional. Maps to <available_actions> in the XML output.

toonSuccess(data)

Creates a standard success response with a TOON-encoded payload via the @toon-format/toon compression schema.

typescript
import { toonSuccess } from '@vinkius-core/mcp-fusion';

return toonSuccess(users);                        // Pipe-delimited natively
return toonSuccess(users, { delimiter: ',' });    // Custom delimiter

Tool Builders

createTool(name) — Builder Pattern

The fluent builder for composing tools with Zod schemas.

typescript
import { createTool } from '@vinkius-core/mcp-fusion';

const tool = createTool<AppContext>('projects');
MethodReturnsDescription
.description(desc)thisThe highest-level tool description summary sent to the LLM.
.discriminator(field)thisOverrides the field key the LLM uses to select operations (default: action).
.annotations(map)thisSets explicit ToolAnnotations (e.g. { readOnlyHint: true }).
.tags(...tags)thisEmbeds categorical tags for ToolRegistry.getTools({ filter }) exclusions.
.toonDescription()thisInjects TOON tabular compression instead of standard Markdown spacing.

Structural Composition

MethodReturnsDescription
.commonSchema(zod)thisAppends a base Zod schema applied identically across every tool branch.
.use(middleware)thisPushes a Global Middleware function to the very top of the execution graph.
.action(config)thisMounts a flat execution route. Incompatible with .group().
.group(name, ...)thisMounts a hierarchical sub-route. Incompatible with .action().

Introspection & Execution

MethodReturnsDescription
.buildToolDefinition()McpToolTriggers framework compilation loop and freezes internal mappings.
.execute(ctx, args)PromiseSafely evaluates discriminator chains and fires the middleware array.
.debug(observer)thisAttaches a DebugObserverFn for pipeline observability. See Observability.
.getActionNames()string[]Dumps native flat keys or dot-notated compound keys.
.getActionMetadata()Object[]Pulls deep context mapping arrays about execution boundaries natively.

defineTool(name, config) — Declarative Config

The JSON-first API for defining tools without Zod imports.

typescript
import { defineTool } from '@vinkius-core/mcp-fusion';

const tool = defineTool<AppContext>('projects', {
    description: 'Manage projects',
    tags: ['core'],
    shared: { workspace_id: 'string' },
    middleware: [authMiddleware],
    actions: {
        list: { readOnly: true, handler: listProjects },
        create: {
            params: { name: { type: 'string', min: 1 } },
            handler: createProject,
        },
    },
    groups: {
        admin: {
            middleware: [requireAdmin],
            actions: { reset: { destructive: true, handler: resetProjects } },
        },
    },
});

Config Fields:

FieldTypeDescription
descriptionstring?Tool description for the LLM.
tagsstring[]?Tags for tag-based filtering.
discriminatorstring?Discriminator field name (default: 'action').
toonDescriptionboolean?Enable TOON token compression for descriptions.
annotationsRecord<string, unknown>?Explicit MCP tool annotations.
sharedParamsMap?Parameters injected into every action.
middlewareMiddlewareFn[]?Global middleware chain.
actionsRecord<string, ActionDef>Action definitions (keyed by action name).
groupsRecord<string, GroupDef>?Nested group definitions.

ActionDef Fields:

FieldTypeDescription
descriptionstring?Action-specific description.
paramsParamsMap | ZodObject?Parameters (JSON shorthand or Zod).
readOnlyboolean?Marks as read-only for LLM.
destructiveboolean?Marks as destructive (⚠️ warning).
idempotentboolean?Marks as safe to retry.
returnsPresenter?MVA Presenter — handler returns raw data.
handler(ctx, args) => Promise<ToolResponse>Required. The action handler.

ParamsMap Shorthand Values:

ValueEquivalent
'string'{ type: 'string' }
'number'{ type: 'number' }
'boolean'{ type: 'boolean' }
{ type, min, max, regex, optional, array, enum }Full descriptor

Middleware

defineMiddleware(deriveFn)

Creates a context-deriving middleware definition (tRPC-style):

typescript
import { defineMiddleware } from '@vinkius-core/mcp-fusion';

const withUser = defineMiddleware(async (ctx: { token: string }) => {
    const user = await verifyToken(ctx.token);
    return { user };  // Merged into ctx
});

// Convert to MiddlewareFn:
tool.use(withUser.toMiddlewareFn());
MethodReturnsDescription
.toMiddlewareFn()MiddlewareFnConverts to a standard middleware function.
.deriveFunctionThe raw derive function.

isMiddlewareDefinition(value)

Type guard to check if a value is a MiddlewareDefinition.

resolveMiddleware(input)

Converts either a MiddlewareDefinition or a plain MiddlewareFn to a MiddlewareFn.


Streaming Progress

progress(percent, message)

Creates a ProgressEvent for use in generator handlers:

typescript
import { progress } from '@vinkius-core/mcp-fusion';

yield progress(50, 'Building project...');
FieldTypeDescription
percentnumberProgress percentage (0–100).
messagestringHuman-readable status message.

isProgressEvent(value)

Type guard to check if a yielded value is a ProgressEvent.

MCP Notification Wiring

When attached to an MCP server via attachToServer(), progress events are automatically forwarded to the MCP client as notifications/progress when the client includes a progressToken in its request _meta. Zero configuration required — the framework detects the token and wires the notifications transparently.

Internal EventMCP Wire Format
yield progress(50, 'Building...'){ method: 'notifications/progress', params: { progressToken, progress: 50, total: 100, message: 'Building...' } }

When no progressToken is present (the client didn't opt in), progress events are silently consumed — zero overhead.

ProgressSink

For direct usage (testing, custom pipelines), ProgressSink is a callable type:

typescript
type ProgressSink = (event: ProgressEvent) => void;

Pass a ProgressSink to builder.execute() or registry.routeCall() as the optional last parameter.


Result Monad

Railway-Oriented Programming for composable error handling. See Result Monad Guide for full patterns.

succeed(value)

Wraps a value into Success<T>:

typescript
import { succeed } from '@vinkius-core/mcp-fusion';

const result = succeed({ id: '1', name: 'Alice' });
// { ok: true, value: { id: '1', name: 'Alice' } }

fail(response)

Wraps a ToolResponse into Failure:

typescript
import { fail, error } from '@vinkius-core/mcp-fusion';

const result = fail(error('User not found'));
// { ok: false, response: ToolResponse }

Types

TypeFieldsDescription
Success<T>ok: true, value: TSuccessful result
Failureok: false, response: ToolResponseFailed result
Result<T>Success<T> | Failure discriminated union

FusionClient

createFusionClient(transport)

Creates a type-safe client for calling tools through a transport layer:

typescript
import { createFusionClient } from '@vinkius-core/mcp-fusion';

type AppRouter = {
    'projects.list': { workspace_id: string };
    'projects.create': { workspace_id: string; name: string };
};

const client = createFusionClient<AppRouter>(transport);

const result = await client.execute('projects.list', { workspace_id: 'ws_1' });

FusionTransport Interface:

typescript
interface FusionTransport {
    callTool(name: string, args: Record<string, unknown>): Promise<ToolResponse>;
}

The client splits dotted action paths: 'projects.list' → tool 'projects' + arg { action: 'list' }.


ToolRegistry

The unified global router that manages attaching and filtering compiled Builders against the actual bare-metal MCP connection arrays.

typescript
import { ToolRegistry } from '@vinkius-core/mcp-fusion';

const registry = new ToolRegistry<AppContext>();
MethodReturnsDescription
.register(builder)voidMounts a single builder and implicitly fires compilation natively.
.registerAll(...)voidMaps variable array of builders seamlessly into memory.
.getAllTools()McpTool[]Returns all registered tool definitions.
.getTools(filter)McpTool[]Filters payload dumps based strictly on inclusion/exclusion tags.
.routeCall(ctx, name, args, progressSink?)PromiseProxies execution requests deeply into the assigned Builder. Optional progressSink forwards generator ProgressEvents.
.enableDebug(observer)voidPropagates a debug observer to ALL registered builders. See Observability.
.has(name)booleanCheck if a tool is registered.
.clear()voidRemove all registered tools.
.sizenumberNumber of registered tools.

.attachToServer(server, options?)

Mounts the registry directly to the underlying MCP Server Protocol instances silently via generic duck-typing logic.

typescript
const detach = registry.attachToServer(server, {
    // Limits the exposure of available Tools strictly to allowed tags:
    filter: { tags: ['public'] },
    
    // Injects highly specific Context variables per MCP execution context:
    contextFactory: (extra) => resolveSessionContext(extra),

    // Enable debug observability for ALL tools (optional):
    debug: createDebugObserver(),
});

// Progress events from generator handlers are automatically sent
// as MCP notifications/progress when the client provides a progressToken.
// No configuration needed — zero overhead when not used.

// Optionally strip handlers gracefully from the server memory on shutdown:
detach();

AttachOptions Fields:

FieldTypeDescription
filterToolFilter?Tag-based inclusion/exclusion filter.
contextFactoryFunction?Per-request context factory. Supports async.
toolExpositionToolExposition?'flat' (default) or 'grouped'. Controls how grouped tools appear on the wire. See Tool Exposition.
actionSeparatorstring?Separator for flat tool names (default: '_'). E.g. '_'projects_list, '.'projects.list.
debugDebugObserverFn?Debug observer — propagated to all builders. See Observability.
stateSyncStateSyncConfig?Cache-control and causal invalidation. See State Sync.

ToolExposition

typescript
type ToolExposition = 'flat' | 'grouped';
ValueBehavior
'flat'Each action becomes an independent MCP tool with isolated schema and annotations.
'grouped'One MCP tool per builder with discriminator enum — optimized for token efficiency and domain cohesion.

ExpositionConfig

typescript
interface ExpositionConfig {
    toolExposition?: ToolExposition;  // Default: 'flat'
    actionSeparator?: string;        // Default: '_'
}

See the full Tool Exposition Guide for details.


Observability

createDebugObserver(handler?)

Factory function that creates a typed debug event observer. See Observability Guide for comprehensive examples.

typescript
import { createDebugObserver } from '@vinkius-core/mcp-fusion';

// Default: pretty console.debug output
const debug = createDebugObserver();

// Custom: forward to telemetry
const debug = createDebugObserver((event) => {
    opentelemetry.addEvent(event.type, event);
});

DebugEvent

Discriminated union of all pipeline events. Use event.type for exhaustive handling.

Event TypeFieldsWhen Emitted
routetool, action, timestampFirst event — incoming call matched
validatetool, action, valid, error?, durationMs, timestampAfter Zod validation
middlewaretool, action, chainLength, timestampBefore middleware chain (only if middleware exists)
executetool, action, durationMs, isError, timestampAfter handler completes
errortool, action, error, step, timestampOn unrecoverable pipeline errors

Builder .debug(observer)

Attach a debug observer to a single tool:

typescript
const tool = createTool<AppContext>('projects')
    .debug(createDebugObserver())
    .action({ name: 'list', handler: listProjects });

State Sync

Prevents LLM Temporal Blindness by injecting cache-control signals into the MCP protocol. See State Sync Guide for comprehensive examples.

StateSyncConfig

typescript
interface StateSyncConfig {
    policies: SyncPolicy[];
    defaults?: { cacheControl?: CacheDirective };
}
FieldTypeDescription
policiesSyncPolicy[]Policy rules, evaluated in declaration order (first match wins).
defaultsobject?Fallback cache directive for unmatched tools.

SyncPolicy

typescript
interface SyncPolicy {
    match: string;
    cacheControl?: CacheDirective;
    invalidates?: string[];
}
FieldTypeDescription
matchstringDot-separated glob pattern (e.g. sprints.*, **.get).
cacheControlCacheDirective?'no-store' or 'immutable' — appended to tool descriptions.
invalidatesstring[]?Glob patterns of tools whose cache is invalidated on success.

CacheDirective

typescript
type CacheDirective = 'no-store' | 'immutable';

ResolvedPolicy

typescript
interface ResolvedPolicy {
    cacheControl?: CacheDirective;
    invalidates?: readonly string[];
}

PolicyEngine

For advanced use cases (custom pipelines, testing).

MethodReturnsDescription
constructor(policies, defaults?)Validates and caches policies
resolve(toolName)ResolvedPolicy | nullResolves the applicable policy (cached)

matchGlob(pattern, name)

Pure function for dot-separated glob matching.

typescript
import { matchGlob } from '@vinkius-core/mcp-fusion';

matchGlob('sprints.*',  'sprints.get');       // true
matchGlob('sprints.*',  'sprints.tasks.get'); // false
matchGlob('sprints.**', 'sprints.tasks.get'); // true
matchGlob('**',         'anything.at.all');   // true

Prompt Engine

Server-side hydrated prompt templates with schema-informed coercion, middleware, and lifecycle sync. See the full Prompt Engine Guide for patterns and examples.

definePrompt(name, config)

Factory for creating type-safe, validated prompt builders:

typescript
import { definePrompt, PromptMessage } from '@vinkius-core/mcp-fusion';

const SummarizePrompt = definePrompt<AppContext>('summarize', {
    title: 'Summarize Document',
    args: { docId: 'string', length: { enum: ['short', 'long'] as const } } as const,
    handler: async (ctx, { docId, length }) => ({
        messages: [
            PromptMessage.system('You are a Technical Writer.'),
            PromptMessage.user(`Summarize document ${docId} (${length}).`),
        ],
    }),
});
ParameterTypeDescription
namestringUnique prompt identifier (slash command name)
config.titlestring?Human-readable display title
config.descriptionstring?Human-readable description
config.argsPromptParamsMap | ZodObject?Argument definitions (flat primitives only)
config.tagsstring[]?Capability tags for RBAC filtering
config.middlewareMiddlewareFn[]?Middleware chain
config.handler(ctx, args) => Promise<PromptResult>Hydration handler
ReturnsPromptBuilder<TContext>Ready for PromptRegistry.register()

Flat Schema Constraint

Prompt arguments must be flat primitives (string, number, boolean, enum). MCP clients render them as visual forms — complex structures cannot be represented. Fetch complex data server-side inside the handler.

PromptMessage

Factory methods for creating MCP-compliant prompt messages:

MethodSignatureDescription
.system(text)(string) => PromptMessagePayloadSystem instruction (encoded as user role per MCP spec)
.user(text)(string) => PromptMessagePayloadUser message
.assistant(text)(string) => PromptMessagePayloadSeed assistant response (multi-turn)
.image(role, data, mimeType)(Role, string, string) => PromptMessagePayloadBase64 image
.audio(role, data, mimeType)(Role, string, string) => PromptMessagePayloadBase64 audio
.resource(role, uri, options?)(Role, string, Options?) => PromptMessagePayloadEmbedded resource
.fromView(builder)(ResponseBuilder) => PromptMessagePayload[]MVA-Driven Prompts — decompose a Presenter view

PromptMessage.fromView(builder) NEW

Decomposes a ResponseBuilder (from Presenter.make() or response()) into XML-tagged prompt messages optimized for frontier LLMs:

typescript
messages: [
    PromptMessage.system('You are a Compliance Officer.'),
    ...PromptMessage.fromView(InvoicePresenter.make(invoice, ctx)),
    PromptMessage.user('Begin the audit.'),
]

Decomposition layers:

OrderXML TagMCP RoleSource
1<domain_rules>systemPresenter.systemRules()
2<dataset>userValidated JSON in code fence
3<visual_context>userUI blocks (ECharts, Mermaid, etc.)
4<system_guidance>systemLLM hints + HATEOAS action suggestions

PromptRegistry<TContext>

Centralized registry for prompt builders with tag filtering and lifecycle sync:

typescript
import { PromptRegistry } from '@vinkius-core/mcp-fusion';

const prompts = new PromptRegistry<AppContext>();
prompts.register(SummarizePrompt);
MethodReturnsDescription
.register(builder)voidRegister a single prompt builder
.registerAll(...builders)voidRegister multiple prompt builders
.getAllPrompts()PromptDefinition[]Get all prompt definitions for prompts/list
.getPrompts(filter)PromptDefinition[]Get filtered prompt definitions
.routeGet(ctx, name, args)Promise<PromptResult>Route a prompts/get request
.notifyChanged()voidNotify clients of catalog changes (debounced)
.has(name)booleanCheck if a prompt is registered
.clear()voidRemove all registered prompts
.sizenumberNumber of registered prompts

Prompt Types

TypeDescription
PromptResult{ description?: string, messages: PromptMessagePayload[] }
PromptMessagePayload{ role: 'user' | 'assistant', content: PromptContentBlock }
PromptContentBlockPromptTextContent | PromptImageContent | PromptAudioContent | PromptResourceContent
PromptBuilder<T>DIP interface: .name, .getDefinition(), .handleGet(), .tags
PromptConfig<T>Configuration for definePrompt()
PromptParamDefUnion of flat primitive descriptors
PromptParamsMapRecord<string, PromptParamDef>
PromptFilter{ tags?, anyTag?, exclude? }

Domain Model Classes

All underlying structural classes use public fields for highly dense, performant direct property access.

Group

Base hierarchical tree node for plotting Tool paths natively.

FieldTypeDescription
parentGroup | nullUpstream target nullated if root block.
childGroupsGroup[]Recursive sub-group tracking arrays.
getFullyQualifiedName()stringSpits out recursive dot-separated identifiers (e.g. root.parent.child).

Tool

The strictly evaluated LLM parameter payload logic.

FieldTypeDescription
inputSchemastringFully expanded JSON Schema string definitions natively.
toolAnnotationsAnnotationsBound behavior hint blocks evaluated by language models.