Skip to content

cxMcpServer

Auto-generated documentation from JSDoc comments

Classes

Objects

Constants

Functions

Typedefs

McpServer

Kind: global class

new McpServer()

MCP Server class for creating AI-tool integrations

mcpServer.McpServer

Kind: instance class of McpServer

new exports.McpServer(name, [version], [debug])

Create a new MCP Server instance

Throws:

  • Error If name is not provided or is not a string
Param Type Default Description
name string Server name displayed to connecting clients (required)
[version] string "'1.0.0'" Server version string
[debug] boolean false Enable debug logging to console

Example

// Create a basic server
const mcp = new McpServer('My AI Tools', '1.0.0');

// Create a server with debug logging
const mcpDebug = new McpServer('Debug Server', '2.0.0', true);

mcpServer.name : string

Server name displayed to clients

Kind: instance property of McpServer

mcpServer.version : string

Server version string

Kind: instance property of McpServer

mcpServer.debug : boolean

Enable debug logging

Kind: instance property of McpServer

mcpServer.tools : Array.<McpTool>

Array of registered tools

Kind: instance property of McpServer

mcpServer.resources : Array.<McpResource>

Array of registered resources

Kind: instance property of McpServer

McpServer.addTool(name, description, handler) ⇒ ParameterBuilder

Register a new tool with the MCP server

Tools are functions that AI models can discover and execute. Each tool has a name, description, and handler function. Parameters can be added using the chainable addParameter method.

Kind: static method of McpServer
Returns: ParameterBuilder - Chainable object with addParameter method
Throws:

  • Error If name is not a string or is empty
  • Error If description is not a string or is empty
  • Error If handler is not a function
  • Error If a tool with the same name already exists
Param Type Description
name string Unique tool identifier (e.g., 'get_weather', 'calculate')
description string Human-readable description for AI context
handler function Async function that executes the tool. Receives an object of arguments.

Example

// Add a simple greeting tool
mcp.addTool('greet', 'Greet a user by name', async ({ name }) => {
  return `Hello, ${name}!`;
}).addParameter('name', 'string', 'The name to greet', true);
Example
// Add a tool with multiple parameters
mcp.addTool('send_email', 'Send an email message', sendEmailHandler)
  .addParameter('to', 'string', 'Recipient email address', true)
  .addParameter('subject', 'string', 'Email subject line', true)
  .addParameter('body', 'string', 'Email body content', true)
  .addParameter('priority', 'string', 'Email priority', false, 'normal', { enum: ['low', 'normal', 'high'] });

McpServer.removeTool(name) ⇒ boolean

Remove a registered tool from the MCP server

Kind: static method of McpServer
Returns: boolean - true if the tool was found and removed, false if not found

Param Type Description
name string Name of the tool to remove

Example

// Remove a tool
const removed = mcp.removeTool('get_weather');
if (removed) {
  console.log('Tool removed successfully');
}

McpServer.addResource(uri, name, handler, [options]) ⇒ McpServer

Register a new resource with the MCP server

Resources are data sources that AI models can discover and read. Each resource has a unique URI, a human-readable name, and a handler function that returns the resource content when requested.

Kind: static method of McpServer
Returns: McpServer - Returns the server instance for method chaining
Throws:

  • Error If uri is not a string or is empty
  • Error If name is not a string or is empty
  • Error If handler is not a function
  • Error If a resource with the same URI already exists
Param Type Default Description
uri string Unique resource URI (e.g., 'file:///config.json', 'db://users/123')
name string Human-readable resource name
handler function Function that returns the resource content (can be async)
[options] Object {} Additional resource options
[options.description] string Description of the resource
[options.mimeType] string "'text/plain'" MIME type of the resource content

Example

// Add a simple text resource
mcp.addResource(
  'config://app/settings',
  'Application Settings',
  () => ({ theme: 'dark', language: 'en' }),
  { description: 'Current application configuration', mimeType: 'application/json' }
);
Example
// Add a dynamic resource that fetches data
mcp.addResource(
  'db://users/current',
  'Current User Profile',
  async () => {
    const user = await fetchCurrentUser();
    return user;
  },
  { description: 'The currently logged in user', mimeType: 'application/json' }
);
Example
// Chain multiple resource registrations
mcp
  .addResource('file:///readme', 'README', () => 'Welcome to the app!')
  .addResource('file:///changelog', 'Changelog', () => 'v1.0.0 - Initial release');

McpServer.removeResource(uri) ⇒ boolean

Remove a registered resource from the MCP server

Kind: static method of McpServer
Returns: boolean - true if the resource was found and removed, false if not found

Param Type Description
uri string URI of the resource to remove

Example

// Remove a resource
const removed = mcp.removeResource('config://app/settings');
if (removed) {
  console.log('Resource removed successfully');
}

McpServer.handle(requestData) ⇒ Promise.<(Object|null)>

Handle an incoming MCP JSON-RPC 2.0 request

This is the main entry point for processing MCP messages. Pass the incoming request data to this method and return the response to the client.

Kind: static method of McpServer
Returns: Promise.<(Object|null)> - The JSON-RPC 2.0 response object, or null for notifications

Param Type Description
requestData Object The JSON-RPC 2.0 request object from the client
requestData.jsonrpc string Must be '2.0'
requestData.method string The MCP method to call (e.g., 'initialize', 'tools/call')
[requestData.params] Object Method parameters
[requestData.id] string | number Request ID (omit for notifications)

Example

// In a ScriptForge handler
export default function main(data) {
  return mcp.handle(data);
}
Example
// Manual request handling
const response = await mcp.handle({
  jsonrpc: '2.0',
  method: 'tools/call',
  params: { name: 'get_weather', arguments: { city: 'London' } },
  id: 1
});

cxMcpServer : object

MCP (Model Context Protocol) Server Implementation

Kind: global namespace
See: https://spec.modelcontextprotocol.io/

Protocol Support

Feature Supported Description
Tools Register and execute custom tools
Resources Register and read data resources
Prompts Prompt templates (extensible)
Notifications Client initialization notifications

Example - Basic Server with Tools

import { McpServer } from '@connexcs/cxMcpServer';

const mcp = new McpServer('Example MCP Server', '1.0.0', true);

function getWeather(args) {
  const { city, units = 'celsius' } = args;
  const temperature = units === 'celsius' ? 22 : 72;
  const unitSymbol = units === 'celsius' ? '°C' : '°F';

  return {
    city,
    temperature: `${temperature}${unitSymbol}`,
    condition: 'Partly cloudy',
    humidity: '65%',
  };
}

function calculate(args) {
  const { expression } = args;
  try {
    const sanitized = expression.replace(/[^\-*0-9+/().\s]/g, '');
    const result = Function(`"use strict"; return (${sanitized})`)();
    return { expression, result };
  } catch (error) {
    throw new Error(`Invalid expression: ${expression}`);
  }
}

mcp.addTool('get_weather', 'Get the current weather for a specified city', getWeather)
  .addParameter('city', 'string', 'The city name to get weather for', true)
  .addParameter('units', 'string', 'Temperature units (celsius or fahrenheit)', false, 'celsius', { enum: ['celsius', 'fahrenheit'] });

mcp.addTool('calculate', 'Perform a mathematical calculation', calculate)
  .addParameter('expression', 'string', 'The mathematical expression to evaluate (e.g., "2 + 2")', true);

export default function main(data) {
  return mcp.handle(data);
}

MCP_PROTOCOL_VERSION : string

MCP Protocol Version - latest stable version supported

Kind: global constant
Default: "'2024-11-05'"

SERVER_CAPABILITIES : Object

Server capabilities configuration object Declares what features this MCP server supports

Kind: global constant
Properties

Name Type Description
tools Object Tool-related capabilities
tools.listChanged boolean Whether tools/list_changed notifications are supported
resources Object Resource-related capabilities
resources.subscribe boolean Whether resource subscriptions are supported
resources.listChanged boolean Whether resources/list_changed notifications are supported
prompts Object Prompt-related capabilities
prompts.listChanged boolean Whether prompts/list_changed notifications are supported

addParameter(paramName, type, paramDescription, [required], [defaultValue], [opts]) ⇒ ParameterBuilder

Add a parameter to the tool's JSON Schema input definition

Parameters define what arguments the tool accepts. Each parameter has a type, description, and optionally a default value and additional JSON Schema constraints.

Kind: global function
Returns: ParameterBuilder - Returns self for method chaining

Param Type Default Description
paramName string Parameter name (used as the key in the arguments object)
type string JSON Schema type: 'string', 'number', 'integer', 'boolean', 'array', or 'object'
paramDescription string Human-readable description of the parameter
[required] boolean false Whether this parameter must be provided
[defaultValue] * Default value if parameter is not provided
[opts] Object {} Additional JSON Schema options
[opts.enum] Array Array of allowed values
[opts.minimum] number Minimum value for numbers
[opts.maximum] number Maximum value for numbers
[opts.minLength] number Minimum string length
[opts.maxLength] number Maximum string length
[opts.pattern] string Regex pattern for string validation

Example

// Required string parameter
.addParameter('name', 'string', 'User name', true)
Example
// Optional number with constraints
.addParameter('count', 'integer', 'Number of items', false, 10, { minimum: 1, maximum: 100 })
Example
// Enum parameter
.addParameter('status', 'string', 'Status filter', false, 'active', { enum: ['active', 'inactive', 'pending'] })

McpTool : Object

Tool definition object

Kind: global typedef
Properties

Name Type Description
name string Unique tool identifier
description string Human-readable tool description
inputSchema Object JSON Schema defining accepted parameters
inputSchema.type string Always 'object'
inputSchema.properties Object Parameter definitions
inputSchema.required Array.<string> List of required parameter names
handler function Function that executes the tool (internal use)

ParameterBuilder : Object

Chainable parameter builder returned by addTool

Kind: global typedef
Properties

Name Type Description
addParameter function Add a parameter to the tool's schema

McpContentItem : Object

MCP tool call result content item

Kind: global typedef
Properties

Name Type Description
type string Content type, typically 'text'
text string The content text/data

McpToolResponse : Object

MCP tool call response

Kind: global typedef
Properties

Name Type Default Description
content Array.<McpContentItem> Array of content items
[isError] boolean false Whether the response represents an error

McpResource : Object

Resource definition object

Kind: global typedef
Properties

Name Type Description
uri string Unique resource URI (e.g., 'file:///config.json', 'db://users/123')
name string Human-readable resource name
[description] string Optional description of the resource
[mimeType] string MIME type of the resource content (e.g., 'application/json', 'text/plain')
handler function Function that returns the resource content