MCP Servers and Tool-Using Agents in Hy

In earlier chapters we gave language models tools in two different ways: we passed Hy functions directly to Ollama’s tool-calling API, and we wrapped a web scraper in an Agno @tool decorator. Both approaches work inside a single program, yet neither lets you share those tools across different applications without rewriting glue code. The Model Context Protocol (MCP) solves that problem. MCP is an open JSON-RPC 2.0 protocol (this chapter targets specification revision 2025-11-25) that defines how a host application discovers and invokes tools, reads resources, and fetches prompt templates from an external server.

The code for this chapter is in the directory source_code_for_examples/nsk_mcp.

What You Will Build

We will build an MCP server and client in Hy from scratch using only the Python standard library, and use it to expose the NSK symbolic knowledge graph engine from the chapter NSK: A Neural-Symbolic Knowledge Graph Engine. Our server speaks newline-delimited JSON-RPC 2.0 over standard input and standard output (stdio), exposes five graph tools (ask, add-fact, graph-stats, explain, and load-facts), publishes the graph’s facts and forward-chaining rules as MCP resources, and provides reusable query templates as MCP prompts. Around the server we place a security boundary (ToolPolicy) with a deny-by-default tool allowlist, result limits, execution timeouts, path-traversal protection on file loading, and a structured JSON Lines (JSONL) audit log written to stderr.

 1 +-------------------------------------------------------------------+
 2 | Host Application (Claude Desktop, IDE, or Hy StdioMcpClient)      |
 3 +-------------------------------------------------------------------+
 4                |                                     ^
 5                | JSON-RPC 2.0 requests (stdin)       | JSON-RPC 2.0 responses (stdout)
 6                v                                     |
 7 +-------------------------------------------------------------------+
 8 | server.hy: serve-stdio -> handle-line -> dispatch (pure function) |
 9 |                                                                   |
10 |   +-----------------------------------------------------------+   |
11 |   | policy.hy: ToolPolicy                                     |   |
12 |   | - allowlist check         - Path.is_relative_to guard     |   |
13 |   | - result limit clamping   - JSONL audit log -> stderr     |   |
14 |   +-----------------------------------------------------------+   |
15 |                               |                                   |
16 |                               v                                   |
17 |   +-----------------------------------------------------------+   |
18 |   | NSK Engine (imported via nsk_path.hy, neural disabled)    |   |
19 |   | - Graph triplestore       - Datalog rules + provenance    |   |
20 |   +-----------------------------------------------------------+   |
21 +-------------------------------------------------------------------+

Why It Matters

When you wire a tool directly into one SDK, three engineering problems appear as soon as the project grows:

  1. Every host needs its own adapter. A function registered for Ollama chat cannot be called by an IDE assistant, a CLI agent, or another team’s orchestrator without writing a new wrapper.
  2. Tools run in the same trust domain as the caller. If a model is tricked by prompt injection into passing "../../etc/passwd" to a file reader or requesting ten million rows from a database, nothing between the model and the Python function stops it unless you build a policy layer yourself.
  3. Testing requires mocking the model or the transport. If tool dispatch is tangled up with network sockets or standard I/O streams, unit tests become slow and brittle.

Implementing the MCP wire protocol directly in Hy shows that there is no magic inside an MCP SDK: every interaction is a plain dictionary sent over a stream. Separating the pure JSON-RPC dispatcher (request dict -> response dict) from the stdio loop lets us test the entire server contract in memory in milliseconds, and then verify the process boundary with a single subprocess test.

The Hy Angle

Hy is well suited to protocol servers and symbolic tool backends:

  • S-expressions as a safe query and data format. Our ask and explain tools accept NSK patterns such as "[?book :author ?who] [?who :codes-in ?lang]", and load-facts reads (:add ...) and (:rule ...) forms from disk. Using hy.read-many with nsk.terms.to-pattern parses these forms into data structures without ever calling eval.
  • Compact dictionary and list comprehensions. JSON-RPC payloads are nested dictionaries and lists. Hy’s lfor, dfor, sfor, and dictionary unpacking ({#** base ...}) build schemas and structured provenance payloads concisely.
  • Direct module reuse. We do not modify a single line of the existing NSK package. A 20-line helper module (nsk_path.hy) adds ../nsk-neural-symbolic-graph to sys.path, imports Graph and run-query, and turns off the Ollama neural fallback so every MCP tool call is deterministic and offline-safe.

Brief Python Equivalent

In Python, dispatching a JSON-RPC request and building a tool response with provenance uses dictionary literals and dictionary comprehensions:

1 # Python
2 def rpc_result(req_id, result):
3     return {"jsonrpc": "2.0", "id": req_id, "result": result}
4 
5 def format_bindings(row):
6     return {k: term_to_json(v) for k, v in row.items()}

In Hy, the same logic uses dfor:

1 ;; Hy
2 (defn rpc-result [req-id result]
3   {"jsonrpc" "2.0" "id" req-id "result" result})
4 
5 (defn format-bindings [row]
6   (dfor [k v] (.items row) k (term-to-json v)))

Run It

Synchronize the environment, run the test suite, and run the client demo from source_code_for_examples/nsk_mcp:

1 cd source_code_for_examples/nsk_mcp
2 uv sync
3 uv run pytest -q
4 uv run hy client.hy

Here is the real output from running the tests and client.hy:

 1 .............                                                            [100%]
 2 13 passed in 0.37s
 3 Connected to nsk-mcp v0.1.0 (protocol 2025-11-25)
 4 Tools: ask, add-fact, graph-stats, explain, load-facts
 5 Initial stats: 21 triples (12 facts, 9 derived), 3 rules
 6 
 7 --- 1. Query with rule provenance (ask) ---
 8   book=nsk, who=mark, lang=lisp  ; rule: ['nsk', 'author', 'mark']
 9   book=nsk, who=mark, lang=hy  ; rule: ['nsk', 'author', 'mark']
10   book=hy-book, who=mark, lang=lisp  ; rule: ['hy-book', 'author', 'mark']
11   book=hy-book, who=mark, lang=hy  ; rule: ['hy-book', 'author', 'mark']
12   book=nsk, who=jane, lang=python  ; rule: ['nsk', 'author', 'jane']
13 
14 --- 2. Explain a rule-derived query (explain) ---
15   {'person': 'mark'} <- [{'triple': ['mark', 'knows-topic', 'mcp'], 'source': 'rule', 'note': 'derived by rule: [:mark :knows-topic :mcp]'}]
16 
17 --- 3. Load allowlisted file (load-facts) ---
18   loaded 4 facts and 0 rules from extra_facts.sexp
19 
20 --- 4. Reject path traversal (load-facts) ---
21   isError=True -> error: path escapes allowlisted data dir: ../../etc/passwd
22 
23 --- 5. Read resource and prompt ---
24   nsk://graph/rules has 3 rules
25   prompt message: Call the `ask` tool with query `[?author :wrote :nsk] [?author :codes-in ?lang]` and summarize the bindings and provenance.

Interpreting the Output

Look closely at the five sections of the demo output:

  1. Handshake and discovery. StdioMcpClient spawns hy server.hy as a child process, sends initialize with protocol version 2025-11-25, follows up with the notifications/initialized notification, and calls tools/list. The server reports 12 asserted facts, 3 rules, and 9 triples derived by forward chaining (21 triples total).
  2. Provenance preservation (ask). The query [?book :author ?who] [?who :codes-in ?lang] joins a rule-derived predicate (:author, derived from [?person :wrote ?work]) with an asserted predicate (:codes-in). Every solution carries its support list in structuredContent, showing which rule triple proved that row.
  3. Rule explanation (explain). Querying [?person :knows-topic :mcp] traces how :mark is linked to :mcp through the rule [?person :knows-topic ?topic] <- [?person :wrote ?work] [?work :covers ?topic].
  4. Path traversal defense (load-facts). Loading "extra_facts.sexp" succeeds because the file resolves inside the allowlisted data/ directory. Passing "../../etc/passwd" is caught by ToolPolicy.resolve-safe-path and returned as an MCP tool error (isError=True) rather than crashing the server or leaking host files.
  5. Resources and prompts. Reading nsk://graph/rules returns the three active Datalog rules as JSON, and prompts/get for find-authors returns a ready-to-use user message instructing an agent how to query the graph.

Seed Data Format

Before looking at the code, inspect source_code_for_examples/nsk_mcp/data/authors.log, which the server loads on startup:

 1 ;; Seed facts for the nsk_mcp server.
 2 (:add :mark :wrote :nsk)
 3 (:add :mark :wrote :hy-book)
 4 (:add :mark :codes-in :lisp)
 5 (:add :mark :codes-in :hy)
 6 (:add :mark :lives-in :sedona)
 7 (:add :jane :wrote :nsk)
 8 (:add :jane :codes-in :python)
 9 (:add :jane :lives-in :oslo)
10 (:add :nsk :uses :unification)
11 (:add :nsk :uses :datalog)
12 (:add :hy-book :covers :mcp)
13 (:add :hy-book :covers :nsk)
14 (:rule [?work :author ?person] [?person :wrote ?work])
15 (:rule [?person :coauthor ?other] [?person :wrote ?work] [?other :wrote ?work])
16 (:rule [?person :knows-topic ?topic] [?person :wrote ?work] [?work :covers ?topic])

And data/extra_facts.sexp holds additional facts that an agent can load on demand with the load-facts tool:

1 ;; Extra facts loaded on demand by the load-facts tool.
2 (:add :ada :wrote :notes-g)
3 (:add :ada :codes-in :analytical-engine)
4 (:add :alan :wrote :computing-machinery)
5 (:add :notes-g :covers :algorithms)

How It Works

1. Reusing NSK Without Modification: nsk_path.hy

To keep a single source of truth for the knowledge graph engine, nsk_path.hy resolves ../nsk-neural-symbolic-graph relative to its own file path, inserts that directory at the front of sys.path, imports the NSK symbols we need, and sets (get nsk.config "enabled") False so ~ predicates never call out to Ollama during MCP requests:

 1 ;; nsk_path.hy -- Locate the NSK example package and disable neural fallback.
 2 
 3 (import sys)
 4 (import pathlib [Path])
 5 
 6 (setv ROOT (.resolve (. (Path __file__) parent))
 7       NSK-DIR (.resolve (/ ROOT ".." "nsk-neural-symbolic-graph"))
 8       DATA-DIR (.resolve (/ ROOT "data")))
 9 
10 (when (not-in (str NSK-DIR) sys.path)
11   (.insert sys.path 0 (str NSK-DIR)))
12 
13 (import nsk)
14 (import nsk.terms [Var Neural show to-term to-pattern to-keyword])
15 (import nsk.store [Graph])
16 (import nsk.query [QueryResult run-query saturate])
17 
18 ;; Disable the Ollama neural fallback for deterministic MCP tool execution.
19 (setv (get nsk.config "enabled") False)

2. The Security Boundary: policy.hy

An MCP server should treat tool arguments as untrusted input. Even when you trust the user, a model can be steered by untrusted text inside a webpage or document to call tools with unexpected arguments. policy.hy defines ToolPolicy, which enforces five controls:

  1. Deny-by-default tool allowlist (check-tool). Only tool names present in self.allowed-tools may be listed or called.
  2. Result limit clamping (clamp-limit). Queries default to 25 rows and are capped at 100 rows so a broad pattern like [?s ?p ?o] cannot flood the client’s context window.
  3. Path-traversal defense (resolve-safe-path). Any relative path passed to load-facts is resolved with Path.resolve and checked with .is-relative-to against self.data-dir. Attempts to escape via .. or symlinks raise PolicyError.
  4. Execution timeouts (run-with-timeout). Each tool call runs inside a single-worker ThreadPoolExecutor with a configurable timeout (2 seconds by default).
  5. Stderr audit logging (audit). Every JSON-RPC method and tool outcome is written as one JSON line to self.audit-stream, which defaults to sys.stderr. In stdio MCP, stdout belongs exclusively to the JSON-RPC wire protocol; writing logs or debug prints to stdout corrupts the stream.

Here is policy.hy:

 1 ;; policy.hy -- Security boundary: allowlists, path validation, limits, audit log.
 2 
 3 (import json)
 4 (import sys)
 5 (import time)
 6 (import concurrent.futures [ThreadPoolExecutor TimeoutError])
 7 (import pathlib [Path])
 8 
 9 (setv DEFAULT-ALLOWED-TOOLS #{"ask" "add-fact" "graph-stats" "explain" "load-facts"}
10       MAX-LIMIT 100
11       DEFAULT-LIMIT 25
12       DEFAULT-TIMEOUT 2.0)
13 
14 
15 (defclass PolicyError [ValueError]
16   "Raised when a tool call violates the server policy.")
17 
18 
19 (defclass ToolPolicy []
20   "Deny-by-default security policy for MCP tool calls."
21 
22   (defn __init__ [self
23                   [allowed-tools None]
24                   [data-dir None]
25                   [max-limit MAX-LIMIT]
26                   [default-limit DEFAULT-LIMIT]
27                   [timeout-seconds DEFAULT-TIMEOUT]
28                   [audit-stream None]]
29     (setv self.allowed-tools (set (if (is allowed-tools None)
30                                       DEFAULT-ALLOWED-TOOLS
31                                       allowed-tools))
32           self.data-dir (.resolve (Path (if (is data-dir None) "data" data-dir)))
33           self.max-limit max-limit
34           self.default-limit default-limit
35           self.timeout-seconds timeout-seconds
36           self.audit-stream (if (is audit-stream None) sys.stderr audit-stream))
37     None)
38 
39   (defn check-tool [self name]
40     "Raise PolicyError if name is not in the allowlist."
41     (when (not-in name self.allowed-tools)
42       (raise (PolicyError f"tool denied by policy: {name}"))))
43 
44   (defn clamp-limit [self requested]
45     "Return a positive result limit bounded by self.max-limit."
46     (when (is requested None)
47       (return self.default-limit))
48     (setv n (int requested))
49     (when (<= n 0)
50       (raise (PolicyError f"limit must be positive, got {n}")))
51     (min n self.max-limit))
52 
53   (defn resolve-safe-path [self rel-path]
54     "Resolve rel-path inside self.data-dir and reject path traversal."
55     (when (or (not (isinstance rel-path str)) (not (.strip rel-path)))
56       (raise (PolicyError "path must be a non-empty string")))
57     (setv candidate (.resolve (/ self.data-dir rel-path)))
58     (when (not (.is-relative-to candidate self.data-dir))
59       (raise (PolicyError f"path escapes allowlisted data dir: {rel-path}")))
60     (when (not (.is-file candidate))
61       (raise (PolicyError f"file not found in data dir: {rel-path}")))
62     candidate)
63 
64   (defn run-with-timeout [self fn #* args]
65     "Run (fn #* args) under a wall-clock timeout."
66     (with [pool (ThreadPoolExecutor :max-workers 1)]
67       (setv future (.submit pool fn #* args))
68       (try
69         (.result future :timeout self.timeout-seconds)
70         (except [TimeoutError]
71           (raise (PolicyError
72                    f"tool timed out after {self.timeout-seconds}s"))))))
73 
74   (defn audit [self event #** fields]
75     "Write one JSONL audit record to self.audit-stream (never stdout)."
76     (setv record {"ts" (round (time.time) 3)
77                   "event" event
78                   #** fields})
79     (.write self.audit-stream (+ (json.dumps record :sort-keys True) "\n"))
80     (.flush self.audit-stream)))

3. Tools and Query Helpers in server.hy

The first half of server.hy converts between JSON values and NSK terms, and implements the five graph tools (tool-ask, tool-add-fact, tool-graph-stats, tool-explain, and tool-load-facts). Notice that parse-query-string and load-sexp-file both use hy.read-many and to-pattern, so an s-expression string from a client can never execute arbitrary code:

 1 (defn parse-query-string [query-str]
 2   "Parse one or more [s p o] patterns from an s-expression string without eval."
 3   (when (or (not (isinstance query-str str)) (not (.strip query-str)))
 4     (raise (ValueError "query must be a non-empty string of [s p o] patterns")))
 5   (setv forms (list (hy.read-many query-str)))
 6   (when (not forms)
 7     (raise (ValueError "query contained no patterns")))
 8   (lfor form forms (to-pattern form)))
 9 
10 (defn result-to-structured [result]
11   "Convert a QueryResult into JSON-friendly bindings and provenance."
12   (setv provenance []
13         rows [])
14   (for [[row used] (zip result.rows result.support)]
15     (.append rows
16       {"bindings" (dfor [k v] (.items row) k (term-to-json v))
17        "support" (lfor [triple source] used
18                    {"triple" (triple-to-json triple)
19                     "source" source})})
20     (for [[triple source] used]
21       (setv item {"triple" (triple-to-json triple) "source" source})
22       (when (not-in item provenance)
23         (.append provenance item))))
24   {"count" (len result)
25    "text" (str result)
26    "solutions" rows
27    "provenance" provenance})
28 
29 (defn tool-ask [graph policy args]
30   (setv query-str (.get args "query")
31         limit (policy.clamp-limit (.get args "limit"))
32         patterns (parse-query-string query-str)
33         result (run-query patterns :graph graph :neural False :limit limit)
34         structured (result-to-structured result))
35   (setv (get structured "limit") limit)
36   structured)
37 
38 (defn tool-load-facts [graph policy args]
39   (setv rel-path (.get args "file" "")
40         safe-path (policy.resolve-safe-path rel-path)
41         [added-facts added-rules] (load-sexp-file graph safe-path))
42   {"file" rel-path
43    "added_facts" added-facts
44    "added_rules" added-rules
45    "total_triples" (len graph)
46    "text" f"loaded {added-facts} facts and {added-rules} rules from {rel-path}"})

4. The Pure JSON-RPC Dispatcher and Stdio Loop in server.hy

MCP uses JSON-RPC 2.0 messages. A request has "jsonrpc": "2.0", an "id", a "method", and optional "params". A notification omits "id" and must not receive a reply. Errors at the protocol layer (such as an unknown method -32601, invalid parameters -32602, or malformed JSON -32700) return a JSON-RPC "error" object. Errors inside a tool call (such as bad query syntax or a policy rejection) return a normal JSON-RPC "result" with "isError": True and an explanation in "content", so the language model can see what went wrong and recover.

In specification revision 2025-11-25, a tools/call result can include both human-readable "content" blocks and machine-readable "structuredContent". Here is the dispatcher and stdio loop from server.hy:

 1 (defn handle-tools-call [graph policy req-id params]
 2   (when (not (isinstance params dict))
 3     (return (rpc-error req-id INVALID-PARAMS "params must be an object")))
 4   (setv name (.get params "name")
 5         args (.get params "arguments" {}))
 6   (when (or (not (isinstance name str)) (not name))
 7     (return (rpc-error req-id INVALID-PARAMS "missing tool name")))
 8   (when (not (isinstance args dict))
 9     (return (rpc-error req-id INVALID-PARAMS "tool arguments must be an object")))
10   (try
11     (policy.check-tool name)
12     (when (not-in name TOOL-HANDLERS)
13       (raise (PolicyError f"unknown tool: {name}")))
14     (setv handler (get TOOL-HANDLERS name)
15           payload (policy.run-with-timeout handler graph policy args))
16     (policy.audit "tool_call" :tool name :status "ok")
17     (rpc-result req-id
18       {"content" [{"type" "text" "text" (get payload "text")}]
19        "structuredContent" payload
20        "isError" False})
21     (except [e [PolicyError ValueError TypeError KeyError]]
22       (policy.audit "tool_call" :tool name :status "error" :reason (str e))
23       (rpc-result req-id
24         {"content" [{"type" "text" "text" f"error: {e}"}]
25          "structuredContent" {"error" (str e) "tool" name}
26          "isError" True}))))
27 
28 (defn dispatch [request graph [policy None]]
29   "Pure JSON-RPC 2.0 dispatcher: (request dict, Graph, ToolPolicy) -> response dict or None.
30   Notifications (requests without an 'id') return None."
31   (setv policy (if (is policy None) (ToolPolicy :data-dir DATA-DIR) policy))
32   (when (or (not (isinstance request dict))
33             (!= (.get request "jsonrpc") "2.0")
34             (not (isinstance (.get request "method") str)))
35     (return (rpc-error (if (isinstance request dict) (.get request "id") None)
36                        INVALID-REQUEST
37                        "invalid JSON-RPC 2.0 request")))
38   (setv method (get request "method")
39         params (.get request "params" {})
40         has-id (in "id" request)
41         req-id (.get request "id"))
42   (policy.audit "rpc_request" :method method :id req-id)
43   (when (not has-id)
44     ;; Notifications never produce a response message.
45     (return None))
46   (cond
47     (= method "initialize")
48       (rpc-result req-id
49         {"protocolVersion" PROTOCOL-VERSION
50          "capabilities" {"tools" {"listChanged" False}
51                          "resources" {"subscribe" False "listChanged" False}
52                          "prompts" {"listChanged" False}}
53          "serverInfo" SERVER-INFO})
54     (= method "ping")
55       (rpc-result req-id {})
56     (= method "tools/list")
57       (rpc-result req-id
58         {"tools" (lfor t TOOL-SCHEMAS
59                    :if (in (get t "name") policy.allowed-tools)
60                    t)})
61     (= method "tools/call")
62       (handle-tools-call graph policy req-id params)
63     (= method "resources/list")
64       (rpc-result req-id {"resources" RESOURCES})
65     (= method "resources/read")
66       (handle-resources-read graph req-id params)
67     (= method "prompts/list")
68       (rpc-result req-id {"prompts" PROMPTS})
69     (= method "prompts/get")
70       (handle-prompts-get req-id params)
71     True
72       (rpc-error req-id METHOD-NOT-FOUND f"method not found: {method}")))
73 
74 (defn handle-line [line graph [policy None]]
75   "Parse one newline-delimited JSON message and return a JSON response string or None."
76   (setv text (.strip line))
77   (when (not text)
78     (return None))
79   (try
80     (setv msg (json.loads text))
81     (except [e json.JSONDecodeError]
82       (return (json.dumps (rpc-error None PARSE-ERROR f"parse error: {e.msg}")))))
83   (setv response (dispatch msg graph policy))
84   (if (is response None)
85       None
86       (json.dumps response)))
87 
88 (defn serve-stdio [[graph None] [policy None] [in-stream None] [out-stream None]]
89   "Run the newline-delimited JSON-RPC stdio loop."
90   (setv graph (if (is graph None) (make-seed-graph) graph)
91         policy (if (is policy None) (ToolPolicy :data-dir DATA-DIR) policy)
92         in-stream (if (is in-stream None) sys.stdin in-stream)
93         out-stream (if (is out-stream None) sys.stdout out-stream))
94   (for [line in-stream]
95     (setv reply (handle-line line graph policy))
96     (when (is-not reply None)
97       (.write out-stream (+ reply "\n"))
98       (.flush out-stream))))

Notice how dispatch and handle-line are decoupled from sys.stdin and sys.stdout. serve-stdio is only ten lines of code at the bottom of the file.

5. The Stdio Client: client.hy

To verify our server from the outside and show how any MCP host interacts with a stdio server, client.hy defines StdioMcpClient. It uses subprocess.Popen with line-buffered text pipes (:bufsize 1, :text True) and implements context-manager methods (__enter__ and __exit__) so the child process is always cleaned up when the with block exits:

 1 (defclass StdioMcpClient []
 2   "A synchronous MCP client that talks to a child process over stdio."
 3 
 4   (defn __init__ [self [command None] [cwd None] [capture-stderr True]]
 5     (setv self.command (if (is command None)
 6                            [sys.executable "-m" "hy" SERVER-PATH]
 7                            (list command))
 8           self.cwd (if (is cwd None) (str HERE) (str cwd))
 9           self.capture-stderr capture-stderr
10           self.proc None
11           self._next-id 0)
12     None)
13 
14   (defn __enter__ [self]
15     (setv self.proc (subprocess.Popen
16                       self.command
17                       :cwd self.cwd
18                       :stdin subprocess.PIPE
19                       :stdout subprocess.PIPE
20                       :stderr (if self.capture-stderr subprocess.PIPE sys.stderr)
21                       :text True
22                       :encoding "utf-8"
23                       :bufsize 1))
24     self)
25 
26   (defn __exit__ [self #* exc-info]
27     (self.close))
28 
29   (defn request [self method [params None]]
30     "Send a JSON-RPC request and wait for the matching response line."
31     (setv self._next-id (+ self._next-id 1)
32           req-id self._next-id
33           msg {"jsonrpc" "2.0" "id" req-id "method" method})
34     (when (is-not params None)
35       (setv (get msg "params") params))
36     (self._send msg)
37     (setv line (.readline self.proc.stdout))
38     (when (not line)
39       (raise (McpClientError f"server closed stdout while waiting for {method}")))
40     (setv resp (json.loads line))
41     (when (in "error" resp)
42       (setv err (get resp "error"))
43       (raise (McpClientError f"RPC error {(get err "code")}: {(get err "message")}")))
44     (get resp "result"))
45 
46   (defn initialize [self]
47     "Run the MCP initialize handshake."
48     (setv res (self.request "initialize"
49                 {"protocolVersion" "2025-11-25"
50                  "capabilities" {}
51                  "clientInfo" {"name" "nsk-hy-client" "version" "0.1.0"}}))
52     (self.notify "notifications/initialized")
53     res)
54 
55   (defn call-tool [self name [arguments None]]
56     (self.request "tools/call"
57       {"name" name
58        "arguments" (if (is arguments None) {} arguments)})))

Connecting to an MCP Host, SDKs, and Remote Transports

Because server.hy speaks standard MCP over stdio, any MCP-capable host (such as Claude Desktop, Cursor, Zed, or an open-source MCP host) can launch it directly using uv:

 1 {
 2   "mcpServers": {
 3     "nsk-graph": {
 4       "command": "uv",
 5       "args": [
 6         "run",
 7         "--directory",
 8         "/path/to/hy-lisp-python-book/source_code_for_examples/nsk_mcp",
 9         "hy",
10         "server.hy"
11       ]
12     }
13   }
14 }

Official mcp Python SDK and Streamable HTTP

We wrote our JSON-RPC dispatcher directly so every protocol message and error code is visible in plain Hy. In larger services you can also import the official Python mcp package (FastMCP) from Hy, or expose the same pure dispatch function over MCP’s Streamable HTTP transport (POST /mcp accepting JSON-RPC messages and returning either application/json or text/event-stream). Because dispatch in server.hy takes a dictionary and returns a dictionary, wrapping it in an HTTP endpoint takes only a few lines of code, and the same ToolPolicy class continues to enforce allowlists, limits, and timeouts. When deploying over Streamable HTTP, always add authentication (such as OAuth 2.1 bearer tokens) and bind to 127.0.0.1 during local development.

Comparing MCP, Direct Function Calling, and Agno Tools

Approach Where we used it Best for Tradeoffs
Direct function calling (ollama.chat :tools [...]) Running Local LLMs Using Ollama Single-script utilities with 2 to 5 local functions Tied to one provider’s SDK; no separate process or resource/prompt primitives
Framework decorator ((defn [tool] ...) in Agno) Agents Using the Agno Agent Framework Rapid single-process agents with built-in prompt loops Coupled to the agent framework; tools live inside the same Python process
MCP server (server.hy over stdio or Streamable HTTP) This chapter (nsk_mcp) Sharing a stateful engine (like NSK) across many hosts, languages, and agents with a clear process and security boundary Slight protocol overhead (process spawn + JSON-RPC serialization)

Tests

The test suite in test_mcp.hy runs without network access or a live model. Twelve tests call dispatch or handle-line directly in memory against JSON fixtures, and one test (test-stdio-client-server-round-trip) spawns the server subprocess over stdio via StdioMcpClient:

 1 (defn make-env [[allowed None] [timeout 2.0]]
 2   "Return #(graph policy audit-buf) for fast in-memory dispatcher tests."
 3   (setv buf (io.StringIO)
 4         graph (make-seed-graph)
 5         pol (ToolPolicy :allowed-tools allowed
 6                         :data-dir DATA-DIR
 7                         :timeout-seconds timeout
 8                         :audit-stream buf))
 9   #(graph pol buf))
10 
11 (defn test-ask-returns-bindings-and-rule-provenance []
12   (setv [graph pol _] (make-env)
13         resp (dispatch {"jsonrpc" "2.0"
14                         "id" 5
15                         "method" "tools/call"
16                         "params" {"name" "ask"
17                                   "arguments" {"query" "[?book :author ?who] [?who :codes-in ?lang]"
18                                                "limit" 10}}}
19                        graph pol)
20         result (get resp "result")
21         structured (get result "structuredContent"))
22   (assert (is (get result "isError") False))
23   (assert (= (get structured "count") 5))
24   (assert (in {"triple" ["nsk" "author" "mark"] "source" "rule"}
25               (get structured "provenance"))))
26 
27 (defn test-policy-rejects-path-traversal []
28   (setv [graph pol buf] (make-env)
29         resp (dispatch {"jsonrpc" "2.0"
30                         "id" 13
31                         "method" "tools/call"
32                         "params" {"name" "load-facts"
33                                   "arguments" {"file" "../../etc/passwd"}}}
34                        graph pol)
35         result (get resp "result"))
36   (assert (is (get result "isError") True))
37   (assert (in "escapes allowlisted data dir"
38               (get (get (get result "content") 0) "text")))
39   (assert (in "\"status\": \"error\"" (.getvalue buf))))
40 
41 (defn test-stdio-client-server-round-trip []
42   (with [client (StdioMcpClient)]
43     (setv init (client.initialize))
44     (assert (= (get init "protocolVersion") PROTOCOL-VERSION))
45     (setv tools (client.list-tools))
46     (assert (= (len tools) 5))
47     (setv ans (client.call-tool "ask"
48                 {"query" "[?who :wrote :nsk] [?who :codes-in ?lang]"}))
49     (assert (is (get ans "isError") False))
50     (setv solutions (get (get ans "structuredContent") "solutions"))
51     (assert (= (len solutions) 3))
52     (setv blocked (client.call-tool "load-facts" {"file" "../../etc/passwd"}))
53     (assert (is (get blocked "isError") True))))

Wrap Up

We built a standards-compliant MCP server and client in Hy without external protocol dependencies, connected it to the NSK knowledge graph engine, and wrapped every tool invocation in an explicit security policy. Keeping the JSON-RPC dispatcher pure (dispatch) made it simple to test both normal graph queries and adversarial inputs in memory before running over stdio.

Optional Practice Problems

  1. Add a remove-fact Tool with Policy Control: Add a remove-fact tool to server.hy that calls graph.remove on a ground [subject predicate object] triple and returns whether the triple was present. Exclude "remove-fact" from DEFAULT-ALLOWED-TOOLS in policy.hy so it is denied by default, and write a test in test_mcp.hy verifying that remove-fact is blocked under the default policy and succeeds only when "remove-fact" is explicitly passed to ToolPolicy.
  2. Expose a Streamable HTTP Endpoint for dispatch: Write a small http_server.hy module using Python’s http.server.BaseHTTPRequestHandler (similar to nsk/server.hy) that accepts POST /mcp requests with a JSON-RPC 2.0 body, passes the parsed dictionary to server.dispatch, and returns HTTP 202 Accepted when dispatch returns None (a notification) or HTTP 200 OK with application/json when dispatch returns a response dictionary. Add a header check requiring an Authorization: Bearer <token> header from an environment variable.

Further Reading