Docs MCP Integration

MCP Integration

Run kynml.mcp.server to expose four compiler tools over the Model Context Protocol stdio transport so agents (Claude, Cursor, and any MCP-compatible client) can author, validate, compile, and run .kyn specs from within a chat session.

Install

pip install 'kynml[mcp]'

Adds mcp>=1.0 to the environment.

Starting the Server

python -m kynml.mcp.server

The server speaks MCP over stdin/stdout. It blocks until the client disconnects. There are no HTTP ports, no authentication, and no persistent state — every tool call is stateless.

Connecting from Claude Desktop

Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or the equivalent on your platform:

{
  "mcpServers": {
    "kynml": {
      "command": "/path/to/.venv/bin/python",
      "args": ["-m", "kynml.mcp.server"]
    }
  }
}

Use the absolute path to the venv interpreter so the optional mcp extra is available.

The Four Tools

kynml_validate

Validate a KynML spec string. Returns "OK" on success or a KynMLError: ... message on failure. Use this before writing a spec to disk.

Input schema:

{
  "spec_text": "<full text of the .kyn spec>"
}

Example tool call:

{
  "name": "kynml_validate",
  "arguments": {
    "spec_text": "dataset D:\n    source = csv(\"data.csv\")\n    target = \"y\"\n\nmodel M:\n    input 4\n    dense 8 relu\n    dense 1 linear\n\ntrain:\n    model = M\n    data = D\n    loss = mse\n    optimizer = adam(lr=0.001)\n    epochs = 10\n    batch = 32"
  }
}

Returns: "OK" or e.g. "KynMLError: <string>:1: Missing train block".


kynml_compile

Compile a KynML spec string into a complete PyTorch Python script. Runs parse + validate + codegen. Returns the script text on success, raises on error.

Input schema:

{
  "spec_text": "<full text of the .kyn spec>"
}

Returns: A Python script string beginning with # Generated by KynML.


kynml_train

Compile and execute a .kyn file on disk. Writes a temporary script, runs it with sys.executable, deletes the temp file, and returns captured stdout + stderr.

Input schema:

{
  "path": "<absolute or relative path to .kyn file>"
}

Returns: Combined stdout/stderr from the training run, or "(no output)" if the script produced nothing.

Example:

{
  "name": "kynml_train",
  "arguments": {
    "path": "/Users/kr/project/examples/house_price.kyn"
  }
}

Returns something like:

Epoch 1/20 - loss: 0.8421
Epoch 2/20 - loss: 0.6103
...
mae: 0.1234
rmse: 0.2100
Saved model to /Users/kr/project/models/house_price_model.pt

kynml_predict

Load a saved PyTorch state dict from disk and run synchronous inference. Does not require a .kyn spec — reconstructs a plain nn.Sequential from the weight keys.

Input schema:

{
  "model_path": "<path to .pt file>",
  "features_json": "<JSON object mapping feature name to float>"
}

Features are sorted by key name before being passed to the model. This must match the column order at training time.

Example:

{
  "name": "kynml_predict",
  "arguments": {
    "model_path": "/Users/kr/project/models/house_price_model.pt",
    "features_json": "{\"bathrooms\": 2.0, \"bedrooms\": 3.0, \"sqft\": 1500.0}"
  }
}

Returns: JSON string: {"prediction": [342150.25]}

How Inference Reconstruction Works

kynml_predict does not require the original model class or .kyn file. It reads the state_dict key names (format: net.0.weight, net.0.bias, net.2.weight, ...), infers layer indices and shapes from the weight tensors, rebuilds a minimal nn.Sequential of nn.Linear layers, loads the weights, and runs forward inference. Activation modules are not stored in the state dict, so only the linear weights survive — activations are inference-irrelevant for scalar outputs and argmax-based classification.

Error Handling

All tool calls are wrapped in a broad except Exception that returns "ERROR: <message>" as the tool result rather than crashing the server. This keeps the MCP session alive across bad inputs.

Dependencies at Runtime

kynml_train and kynml_predict both require torch. The server will return "ERROR: torch not installed" from kynml_predict if torch is absent. kynml_validate and kynml_compile are torch-free — they only need the core KynML package.

See Also

  • Architecture — where the MCP server sits in the package layout
  • Serving — deploy a trained model as a REST service
  • Cookbook — agent-driven training workflow recipes