Spanish Total.js
English
Documentation For AI agents
Contents

MCP server

Expose actions as tools for AI clients with the built-in MCP endpoint POST /$mcp/ and protect it with Total.mcp.auth; GET /$mcp/client.js gives agents the tools as code.

.md GitHub
On this page

The Model Context Protocol (MCP) lets an AI client, such as an assistant, an agent or an editor, find the tools of a server and call them. Total.js 5 has an MCP server: it turns your actions into tools. Set the configuration key $mcp and add mcp: true to the actions that the AI may use.

# config
name     : Tasks
version  : 1.0
$mcp     : true
// actions/tasks.js
NEWACTION('Tasks|create', {
    summary: 'Creates a task and returns its ID',
    mcp: true,
    input: '*name:String // The name of the task, due:Date // When the task must be done',
    output: 'id:UID',
    action: function($, model) {
        model.id = UID();
        NOSQL('tasks').insert(model).callback(() => $.callback({ id: model.id }));
    }
});

NEWACTION('Tasks|remove', {
    summary: 'Removes a task',
    mcp: true,
    params: '*id:UID // The ID of the task',
    action: function($) {
        NOSQL('tasks').remove().id($.params.id).callback(function(err, count) {
            if (count)
                $.success();
            else
                $.invalid(404);
        });
    }
});

The AI client connects to http://localhost:8000/$mcp/ and sees the tools Tasks_create and Tasks_remove.

The endpoint

With $mcp : true the framework creates the route POST /$mcp/ when the application is ready. Set the key in the config file (or in code before the start); without it the URL answers 404.

The endpoint speaks JSON-RPC 2.0 over HTTP. Each request is one JSON-RPC message and the answer is one JSON object with content-type: application/json. The server keeps no session and sends no stream, so GET /$mcp/ gives 404. A request can have up to 10 MB and can take up to 300 seconds. In the settings of an AI client, choose the HTTP transport and enter the URL of the endpoint.

MethodAnswer
initializeThe protocol version, capabilities: { tools: {} } and serverInfo with CONF.name and CONF.version
pingAn empty result
tools/listThe list of the tools
tools/callRuns a tool (an action) and returns its response
server/discoverThe supported version 2026-07-28, the capabilities and the server info
a notification (a message without id)Status 202 without a body

Another method gets the error -32601 (Method not found). A message without "jsonrpc": "2.0" or without a method, or a JSON array (a batch), gets -32600 (Invalid Request).

// the answer to { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18" } }
{ "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2025-06-18", "capabilities": { "tools": {} }, "serverInfo": { "name": "Tasks", "version": "1.0" } } }

initialize answers with the version that the client asks for when it is in Total.mcp.versions (2026-07-28, 2025-11-25, 2025-06-18, 2025-03-26), and with the first one otherwise.

Actions as tools

Every action with mcp: true is a tool. The list is built again 200 ms after each NEWACTION(), so the actions of plugins and of later code are in it too.

  • name: the name of the action with each character other than a letter, a digit, _ and - replaced by _, at most 64 characters. Tasks|create is Tasks_create.
  • description: the summary option of the action, or its name option.
  • inputSchema: an object with up to three keys, input, query and params, made from the schemas of the action. A key is required when its schema has a required field.
  • outputSchema: made from the output schema, when the action has one.

The fields are converted to standard JSON Schema. The // message of a field is its description, so write messages that tell the AI what to send (a message ends at the next comma, so it can't contain one). Date is a string with format: 'date-time', Email has format: 'email', an enum keeps its values, and a type that can be null (String2, UID, JSON and others) gets the type ['string', 'null']. Every field of params is a string.

// tools/list, the tool Tasks_remove
{
    "name": "Tasks_remove",
    "description": "Removes a task",
    "inputSchema": {
        "type": "object",
        "properties": {
            "params": {
                "type": "object",
                "description": "URL params passed to this action.",
                "properties": { "id": { "type": "string", "description": "The ID of the task" } },
                "additionalProperties": false,
                "required": ["id"]
            }
        },
        "required": ["params"]
    }
}

F.actions[name].toAITool() returns the same definition for one action, and Total.mcp.tools holds the whole list.

Calling a tool

The AI client sends tools/call with the name of the tool and its arguments: input (the payload; data is accepted too), query and params.

{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "Tasks_create", "arguments": { "input": { "name": "Call Peter", "due": "2026-11-20" } } } }

The framework runs the action with ACTION(), so the schemas validate the arguments as for any other call. There is no controller, and the user of the action is the user that Total.mcp.auth accepted the request with (see below). With the default function it is { id: 'ai', name: 'AI', sa: true }: the user: true, sa and permissions checks pass, and an action with user: false fails with 401. The id from the query string of the endpoint (/$mcp/?id=...) is in $.config.id.

The response of the action is sent as text: a string as it is, any other value as JSON. When the response is an object (not an array), it is also in structuredContent:

{ "jsonrpc": "2.0", "id": 3, "result": { "resultType": "complete", "content": [{ "type": "text", "text": "{\"id\":\"JafvB11cV61f\"}" }], "structuredContent": { "id": "JafvB11cV61f" } } }

Errors of validation and of $.invalid() come back as a result with isError: true and the JSON array of the errors as text, so the AI can read them and try again:

{ "jsonrpc": "2.0", "id": 6, "result": { "resultType": "complete", "content": [{ "type": "text", "text": "[{\"error\":\"404: Not Found\"}]" }], "isError": true } }

An unknown tool, or an action without mcp: true, gets the error -32602 (Unknown tool: name); arguments that are not an object get -32602 too. Report errors with $.invalid(). An exception thrown in the action (also in an async one) is written to the error log, and the client gets a result with isError: true and a short message (Tool execution failed, or 500: Internal Server Error for an async action), without the details of the exception.

Authorization

By default every request is allowed. Anyone who can reach the URL can run the tools, and the tools run as the super admin { id: 'ai', name: 'AI', sa: true }, so protect the endpoint with Total.mcp.auth. The function gets $ with the token from the Authorization header ($.token, without Bearer ), $.headers, $.query and $.ip. Call $.success(user) to accept the request or $.invalid() to refuse it.

// definitions/mcp.js
Total.mcp.auth = function($) {
    if ($.token && $.token === CONF.mcptoken)
        $.success({ id: 'mcp' });
    else
        $.invalid();
};

A refused request gets status 401 and the JSON-RPC error -32001 (Unauthorized). The tools run as the user given to $.success(user), so the user, sa and permissions checks of the actions apply to that user. $.success() without a user gives an empty user {}.

Total.mcp.filter decides which tools each caller may use. It gets the definition of a tool and $ with the caller in $.user, and returns true to allow the tool. A tool that is not allowed is not in tools/list, and calling it gives -32602 (Unknown tool):

// definitions/mcp.js
Total.mcp.auth = function($) {
    if ($.token === CONF.mcp_admin)
        $.success({ id: 'admin', name: 'Admin', sa: true });
    else if ($.token === CONF.mcp_reader)
        $.success({ id: 'reader', name: 'Reader' });
    else
        $.invalid();
};

Total.mcp.filter = function(tool, $) {
    return !tool.name.startsWith('Admin_') || $.user.sa;
};

Code mode

Every tool call goes through the model: the definitions of all tools are sent with each request, and every result comes back into the conversation. With many tools or big results that costs many tokens. In code mode the agent writes a small script that calls the tools, runs it on its side (a shell, a sandbox) and only the output of the script reaches the model.

GET /$mcp/client.js returns the tools of the caller as a JavaScript module: one function per tool, with JSDoc that describes the arguments and the result, written from the same schemas as tools/list. It is on whenever $mcp is on and goes through the same Total.mcp.auth and Total.mcp.filter, so the file has exactly the tools that the token may use:

curl -H 'Authorization: Bearer TOKEN' https://app.example.com/$mcp/client.js > client.js
// /**
//  * Creates a task and returns its ID
//  * @param {Object} args
//  * @param {Object} args.input Payload (request body) passed to this action.
//  * @param {String} args.input.name The name of the task
//  * @param {String} [args.input.due] When the task must be done (ISO date)
//  * @returns {Promise<{ id: ?String }>}
//  */
// api.Tasks_create = args => call("Tasks_create", args);

const api = require('./client.js')('TOKEN');

for (const name of ['Call Peter', 'Send the offer'])
    await api.Tasks_create({ input: { name } });

console.log('2 tasks created');

require('./client.js')(token, [url]) returns the functions. Each one sends tools/call to POST /$mcp/ with the token, resolves with the output of the tool and throws an Error with the message of a tool error. The client needs Node.js 18 or newer and no packages. With ?q=words the file has only the tools whose name or description contain all the words, so an agent can read just what it needs: /$mcp/client.js?q=task.

Nothing runs on the server: the script runs where the agent runs, and every call is a normal tool call with the permissions of the token.

Made in Europe