NAME

Logic::Relational::MCP - Model Context Protocol (MCP) server for Logic::Relational knowledge bases

VERSION

Version 0.10

SYNOPSIS

use v5.38;
use Logic::Relational::Syntax;
use Logic::Relational::MCP;

logic HospitalKB {
    description 'Hospital Staffing & Clinical Duty Roster';
    program_version '1.0.0';

    predicate role => (
        doc  => 'Clinical role classification (doctor, nurse, surgeon)',
        args => ['name', 'title'],
    );

    facts {
        role('Alice', 'doctor');
        role('Bob',   'nurse');
    }
}

# One-line stdio MCP server (for Claude Desktop, Cursor, LM Studio):
Logic::Relational::MCP->serve('HospitalKB');

# Or HTTP MCP server:
Logic::Relational::MCP->serve(
    'HospitalKB',
    transport => 'http',
    port      => 3000,
);

# Or OO interface for Mojolicious mounting and custom domain tools:
my $mcp = Logic::Relational::MCP->new(
    program        => 'HospitalKB',
    include_stdlib => 0,
    max_steps      => 20_000,
);
$mcp->to_stdio;

DESCRIPTION

Logic::Relational::MCP wraps any Logic::Relational::Program (or declarative logic MyKB { ... } package) and serves it as a standard Model Context Protocol (MCP) server powered by MCP::Server.

It uses the metadata, docstrings, schema reflection (describe), and JSON-Datalog query interface (query_data) introduced in Logic::Relational v0.04 to provide read-only, safety-bounded relational querying to LLMs with minimal configuration.

METHODS

new

my $mcp = Logic::Relational::MCP->new(
    program        => 'HospitalKB',   # package name or Logic::Relational::Program
    prefix         => 'kb_',          # tool name prefix (default: 'kb_')
    include_stdlib => 0,              # default: 0
    expose         => undef,          # optional arrayref allowlist
    hide           => undef,          # optional arrayref denylist
    default_limit  => 50,             # default row limit
    max_limit      => 200,            # hard ceiling on client-supplied limit
    max_steps      => 50_000,         # hard ceiling on resolution steps
    max_timeout_ms => 5_000,          # hard ceiling on wall-clock timeout (ms)
    read_only      => 1,              # default: 1 (enforced in v0.10)
    name           => undef,          # override MCP server name
    version        => undef,          # override MCP server version
    instructions   => undef,          # override MCP server instructions
    server         => undef,          # optional pre-built MCP::Server
);

Constructs a new Logic::Relational::MCP bridge instance and registers MCP tools, resources, and prompts on the underlying MCP::Server.

serve

Logic::Relational::MCP->serve($program_or_package, %options);

Convenience class method that instantiates Logic::Relational::MCP and starts the requested transport loop. Supports transport => 'stdio' (default) or transport => 'http' (with host, port, path, and log_level).

to_stdio

Starts the blocking MCP stdio transport loop (reads JSON-RPC from STDIN, writes to STDOUT).

to_action

my $action = $mcp->to_action(\%options);

Returns a Mojolicious route action subref for mounting the MCP endpoint in an existing web application.

handle

my $response = $mcp->handle($json_rpc_request, $context);

Dispatches a single JSON-RPC request in-process through the underlying MCP::Server. Useful for unit testing and embedded integrations.

filtered_describe

Returns the program's describe() schema hashref filtered according to include_stdlib, expose, and hide, augmented with a capabilities block.

is_predicate_visible

my $bool = $mcp->is_predicate_visible($pred_name, $arity);

Returns true if the predicate is permitted by the server's expose/hide filters.

Accessors

program, server, prefix, name, version, read_only, include_stdlib, default_limit, max_limit, max_steps, max_timeout_ms, expose, hide.

MCP SURFACE

Out of the box, Logic::Relational::MCP registers the following MCP primitives (using the configured prefix, which defaults to kb_):

  • Tools:

    • kb_describe - Returns the filtered schema (program metadata, capabilities, and predicate descriptors with argument names, types, docstrings, and ground_required). Optionally accepts { predicate => "name" | "name/arity" } to inspect a single predicate.

    • kb_query - Executes a read-only JSON-Datalog conjunctive query with negation-as-failure, variable projection (select), set deduplication (distinct), and server-enforced max_limit, max_steps, and max_timeout_ms ceilings.

  • Resources:

    • logic://<slug>/schema (application/json) - Live filtered schema.

    • logic://<slug>/guide (text/markdown) - Auto-generated query guide synthesized from the knowledge base's actual predicates and server limits.

  • Prompts:

    • consult_knowledge_base - Reusable workflow prompt guiding an LLM to inspect the schema first and ground its answer strictly in query results.

You can register additional domain-specific tools, resources, or prompts on the underlying MCP::Server via $mcp->server->tool(...).

DOCUMENTING YOUR KNOWLEDGE BASE FOR LLMS

Because an LLM relies on kb_describe and the server instructions to understand what your knowledge base contains and how to query it, clear metadata inside your Logic::Relational program directly improves query accuracy - especially with smaller local models.

Using Logic::Relational::Syntax (v0.04+):

logic InventoryKB {
    description 'Warehouse stock levels, supplier lead times, and reorder rules';
    program_version '1.0.0';

    predicate sku_stock => (
        doc  => 'Current on-hand quantity for a product SKU (e.g. "SKU-100", 42)',
        args => [
            { name => 'sku',      type => 'string',  description => 'Product SKU code (e.g. SKU-100)' },
            { name => 'quantity', type => 'integer', description => 'Units currently in stock' },
        ],
    );

    predicate needs_reorder => (
        doc             => 'True when a SKU is below its safety threshold (arg 0 must be bound)',
        ground_required => [0],
        args            => ['sku'],
    );
}

Or programmatically on a Logic::Relational::Program instance:

my $prog = Logic::Relational::Program->new(
    name        => 'InventoryKB',
    version     => '1.0.0',
    description => 'Warehouse stock levels, supplier lead times, and reorder rules',
);
$prog->set_predicate_metadata(
    'sku_stock/2',
    {
        doc  => 'Current on-hand quantity for a product SKU (e.g. "SKU-100", 42)',
        args => [ 'sku', 'quantity' ],
    }
);

Practical tips for LLM-friendly schemas:

  • Include concrete value examples in doc and argument descriptions: If a predicate expects canonical strings (e.g. "Doctor" rather than "Dr", or "lower_back" rather than "Lower Back"), include 2-3 real examples or list closed enum values directly in doc.

  • Be literal and unambiguous: LLMs take predicate descriptions at face value. Avoid mentioning concepts or statuses (such as "active or inactive") unless there is actually a predicate or argument that distinguishes them.

  • Declare ground_required on constrained rules: For rules that use internal negation or require a bound lookup key, specify zero-based argument indices in ground_required => [ ... ] so the query planner rejects unbound calls cleanly instead of floundering.

  • Hide internal helper predicates: Use hide or expose when creating the MCP server so internal recursive helpers or low-level table generators do not clutter the schema returned by kb_describe.

DYNAMIC KNOWLEDGE BASES VIA GENERATORS

Although Logic::Relational::MCP v0.10 exposes a read-only MCP interface, your underlying knowledge base does not have to be static.

By backing predicates with Logic::Relational generators - for example, querying a live SQLite, MariaDB, or PostgreSQL table, or reading live telemetry/APIs - each incoming MCP query evaluates against the latest external state automatically:

$program->generator(
    'sensor_reading', 3,
    sub ($sensor, $metric, $value) {
        my (@where, @binds);
        if (defined $sensor && !ref($sensor)) {
            push @where, 'sensor_id = ?';
            push @binds, $sensor;
        }
        my $sql = 'SELECT sensor_id, metric, value FROM readings';
        $sql .= ' WHERE ' . join(' AND ', @where) if @where;
        my $sth = $dbh->prepare($sql);
        $sth->execute(@binds);
        return sub {
            my $row = $sth->fetchrow_arrayref // return;
            return [@{$row}];
        };
    }
);

Because Logic::Relational creates a fresh per-query tabling cache for every query_data() call, tabled rules built on top of dynamic generators will not serve stale results across MCP calls.

Tips for long-running SQL-backed MCP servers:

  • Keep AutoCommit => 1 on read handles so engines such as MariaDB/InnoDB do not hold an open snapshot transaction that hides newly committed rows.

  • Guard against database idle timeouts (e.g. MariaDB wait_timeout) by pinging and reconnecting lazily inside your generator or enabling driver auto-reconnect.

  • External processes can write to the SQL database concurrently using standard RDBMS locking, transactions, and credentials while Logic::Relational::MCP provides the deductive reasoning layer for LLMs.

SEE ALSO

Logic::Relational, Logic::Relational::Manual::JSONDatalog, MCP::Server

AUTHOR

Matt Johnson <mjohnson@affectivesilicon.com>

AI

This module was developed with assistance from Gemini 4 Neon.

LICENSE AND COPYRIGHT

This software is Copyright (c) 2026 by Matt Johnson. This is free software, licensed under the GNU General Public License, Version 3.