CMSIS-MCP  Version 0.0.0
Embedded MCP server with serial transport
 
Loading...
Searching...
No Matches
Tool registration and callbacks

Describe tools for clients and bind validated inputs to callbacks. More...

Typedefs

typedef int(* mcp_tool_fn) (int argc, const char **returnMessage, const char **args)
 Callback invoked for a validated tools/call request.
 

Functions

int set_tool_callback (struct tool *tool, mcp_tool_fn callback)
 Bind the callback invoked when a client calls a registered tool.
 
struct tool * find_tool (const char *name)
 Look up a registered tool by exact, case-sensitive name.
 
void add_argument (struct tool *tool, const char *name, enum type type, const char *description)
 Append one required argument to a tool's discovery schema.
 
struct tool * add_tool (const char *name, const char *description)
 Register a tool name and its client-visible description during startup.
 

Description

Describe tools for clients and bind validated inputs to callbacks.

Typedef Documentation

◆ mcp_tool_fn

typedef int(* mcp_tool_fn) (int argc, const char **returnMessage, const char **args)

Callback invoked for a validated tools/call request.

Parameters
[in]argcNumber of registered arguments, validated before invocation.
[out]returnMessageSet *returnMessage to null-terminated response text.
[in]argsArray of argc strings in add_argument() registration order. NULL when argc is zero; no extra sentinel element.
Returns
0 for success. Codes -32700 through -32600 produce a JSON-RPC error. Other negative values produce a tool result with isError=true. Positive status or missing output produces MCP_INTERNAL_ERROR.

All arguments are required. The core rejects missing, extra, duplicate and incorrectly typed inputs before invocation, so argc is redundant for a fixed-signature callback and a defensive count check is optional. Strings are decoded JSON text, booleans are "true"/"false", and finite numbers are JSON-compatible numeric text (possibly exponent notation). The callback must validate ranges/enumerations before applying changes.

Warning
Input strings are borrowed for this request. Output must reference static text or request-arena text, not an automatic local buffer. Never retain input/output pointers after dispatch or free arena memory.
See also
add_tool for a complete callback and registration example.

Function Documentation

◆ add_argument()

void add_argument ( struct tool * tool,
const char * name,
enum type type,
const char * description )
extern

Append one required argument to a tool's discovery schema.

Parameters
[in]toolValid handle returned by add_tool() or find_tool().
[in]nameNonempty input key, unique among the tool's argument names.
[in]typeJSON input type: TYPE_STR, TYPE_INT, TYPE_FLOAT or TYPE_BOOL.
[in]descriptionMeaning, units, limits or choices; NULL omits the property's description.

tools/list places the argument in inputSchema.properties and its name in inputSchema.required. TYPE_INT advertises integer; TYPE_FLOAT advertises number. Descriptions do not generate enum/minimum/maximum constraints: enforce these in the callback. Callback order is the order of add_argument() calls.

Note
This function has no return value. Invalid definitions, duplicate names or allocation failure during registration make mcp_prepare() fail. Calls after successful preparation or during dispatch are ignored. Strings are borrowed until free_tools().
Example
add_argument(tool, "on", TYPE_BOOL, "true enables; false disables");
add_argument(tool, "color", TYPE_STR, "Colour name: red, green or blue");
// args[0] = on, args[1] = color.
void add_argument(struct tool *tool, const char *name, enum type type, const char *description)
Append one required argument to a tool's discovery schema.
@ TYPE_STR
JSON string; callback receives decoded text.
Definition mcp.h:67
@ TYPE_BOOL
JSON boolean; callback receives "true" or "false".
Definition mcp.h:70
The colour property advertised in tools/list is:
{"type":"string","description":"Colour name: red, green or blue"}
See also
add_tool for the complete registration example.

◆ add_tool()

struct tool * add_tool ( const char * name,
const char * description )
extern

Register a tool name and its client-visible description during startup.

Parameters
[in]nameUnique, nonempty, case-sensitive name used in tools/call.
[in]descriptionHuman-readable behavior and effects; NULL omits this field from tools/list.
Returns
Borrowed tool handle, or NULL for an invalid/duplicate name, allocation failure or registration after preparation/during dispatch.

The description becomes the tool's description field in tools/list. Explain what the tool changes/reads, side effects and when changes take effect. Argument meanings, units and accepted values belong in add_argument() descriptions. These strings are metadata: they are not parsed as commands or schemas, and they do not implement validation.

Register arguments and a callback before mcp_prepare(). All registration strings are borrowed and must remain valid and unchanged until free_tools(). No callback or argument is created implicitly.

Complete example: describe, validate and register a tool
#include "mcp.h"
#include <string.h>
static int indicator_on;
static unsigned indicator_rgb;
static int set_indicator(int argc, const char **message, const char **args)
{
unsigned rgb;
// args[0] is on, args[1] is color, regardless of JSON key order.
if (argc != 2) { // Optional; the core already validates required inputs.
*message = "Expected on and color";
}
if (!strcmp(args[1], "red")) rgb = 0xff0000;
else if (!strcmp(args[1], "green")) rgb = 0x00ff00;
else if (!strcmp(args[1], "blue")) rgb = 0x0000ff;
else {
*message = "color must be red, green or blue";
}
// Validate everything before applying changes. A board's main loop can
// consume these example settings; do not retain pointers from args.
indicator_rgb = rgb;
indicator_on = !strcmp(args[0], "true");
*message = "Indicator settings updated"; // Static text is valid.
return 0;
}
static int register_indicator(void)
{
struct tool *tool = add_tool("setIndicator",
"Set the indicator colour and enable state. Changes apply on the next update.");
if (!tool || set_tool_callback(tool, set_indicator) != 0) {
return -1;
}
add_argument(tool, "on", TYPE_BOOL,
"true enables the indicator; false disables it");
add_argument(tool, "color", TYPE_STR, "Colour name: red, green or blue");
if (mcp_prepare() != 0) { // Also detects failed argument registration.
return -1;
}
return 0;
}
void free_tools(void)
Release tool/resource registries and cached responses; reopen registration.
int mcp_prepare(void)
Finish startup by caching discovery schemas and response templates.
struct tool * add_tool(const char *name, const char *description)
Register a tool name and its client-visible description during startup.
int set_tool_callback(struct tool *tool, mcp_tool_fn callback)
Bind the callback invoked when a client calls a registered tool.
#define MCP_INVALID_PARAMS
JSON-RPC invalid parameters: missing, extra or invalid input (-32602).
Definition mcp.h:84
Public API for the portable C MCP server.
A client can call this tool with the following request. Reversing the JSON keys does not change callback argument order:
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"setIndicator","arguments":{"color":"green","on":true}}}

◆ find_tool()

struct tool * find_tool ( const char * name)
extern

Look up a registered tool by exact, case-sensitive name.

Parameters
[in]nameTool name; NULL is permitted and has no match.
Returns
Borrowed handle, or NULL if absent. Valid until free_tools().

Does not allocate memory.

Example
struct tool *tool = find_tool("setIndicator");
struct tool * find_tool(const char *name)
Look up a registered tool by exact, case-sensitive name.

◆ set_tool_callback()

int set_tool_callback ( struct tool * tool,
mcp_tool_fn callback )
extern

Bind the callback invoked when a client calls a registered tool.

Parameters
[in]toolValid registered tool handle.
[in]callbackNon-NULL callback.
Returns
0 on success; -1 for NULL inputs or after preparation/during dispatch.

May replace a callback during startup. A tool without a callback can appear in discovery, but calling it produces MCP_INTERNAL_ERROR.

Example
if (set_tool_callback(tool, set_indicator) != 0) { free_tools(); return -1; }