Hooks, plugins and MCP servers
How oklm agent is extended from outside: hooks that run
on its events, plugins that bundle commands, skills, agents, hooks and
servers, and MCP servers whose tools, resources and prompts join a
session. Part of the agent harness (harness.md); a how-to for writing them is in extending.md.
Status: implemented.
Hooks
include/oklm/harness/hooks.h,
src/harness/hooks.c: commands the hooks
setting attaches to the agent's events, merged from every settings
file.
"hooks": {
"PreToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "./scripts/lint.sh", "timeout": 60 } ] } ]
}- Events:
SessionStart(sourcestartup,resume,clear),SessionEnd(reasonexit,clear),UserPromptSubmit(prompt),PreToolUseandPostToolUse(tool_name,tool_input, andtool_responsewith itsstatusandoutput),Notification(message: a question waits, a long turn ended),StopandSubagentStop(stop_hook_active),PreCompact(triggermanualorauto,custom_instructions),ProcessStartandProcessExit(id,kind,label,command, and for an exitstateandexit_code; matched on the kind:command,monitor,mcp,lsp...),MonitorEvent(event: the background events about to reach the model; a block drops them),ServiceReady(name,idits job,pid,portsthe declared ones or else those it listens on,probeits readiness probe as declared; matched on the service's name; once each time a declared service passes its readiness probe, a service without one never does),WorktreeCreate(name,base,path: it makes the worktree instead of git and prints the path it made, its last line of output) andWorktreeRemove(path,branch: it removes a worktree a hook made, and is told when git removes one of its own). The process hooks run on the main thread when it looks at the processes: between turns, while waiting for the user, in a headless run's event loop; a process that starts and ends while the agent works is seen at its turn's end. - Matchers: alternatives between
|, each a name or a pattern where*and.*stand for anything (Notebook.*); empty or*matches all. Matched against the tool for the tool events, the source, the reason or the trigger for the others. - Running: the event as JSON on the standard input
(
session_id,transcript_path,cwd,hook_event_nameand its own fields), in the project withOKLM_PROJECT_DIRset, not confined (the user's own commands), within its timeout (60 s). The matching hooks run at once, each command once. - Answers: exit 0 succeeds, its output added to the
context for
UserPromptSubmitandSessionStart; exit 2 blocks, its error output the reason: a call refused (Blocked by a PreToolUse hook: ..., given to the model, audited with the rulehook), a result followed byPostToolUse hook: ..., a message not sent ([blocked by a UserPromptSubmit hook: ...]), the agent sent back to work byStop(A hook keeps you from stopping yet: ..., five times at most for a message). Another code shows its error to the user, nothing blocked; so does a timeout. A JSON object decides instead:decision(block, orapprove: the call runs without a question, a deny rule or a dangerous call still stopping it),reason,continue: falsewithstopReason,additionalContext,updatedInput(the call's new arguments),hookSpecificOutput.permissionDecision(allow,deny) with its reason. The user's own!commands run no hook. /hookslists them by event with their matcher, command, timeout and the settings files holding them; when the settings changed since the session started it says so, the session keeping the hooks it started with until/hooks reload. They run once the folder is trusted (the interactive trust question);-pasks nothing.
tests/harness/test_hooks.c: matchers; the settings read
(an unknown event, a hook of another type, timeouts); exit 0 adding
context, the input as given (session, transcript, event, fields), exit 2
blocking with its reason, another code shown; JSON answers
(approve with new arguments and context,
continue: false, permissionDecision: deny); no
matcher, no run; a command given twice run once, three hooks of a second
each done within 2.5 s, OKLM_PROJECT_DIR, a timeout; around
the tools, the acceptance: a PreToolUse hook refusing Write
and Edit on *.lock (other files go through), a
PostToolUse formatter stripping the trailing blanks after
Write and Edit, new arguments sending a write
elsewhere, a PostToolUse block reaching the model, an approval running a
command no one would have allowed, the user's own command running no
hook; in the agent, a message given the hook's context, another refused
and kept out of the conversation, a Stop hook sending it back once (then
stop_hook_active lets it stop), PreCompact's input. Checked
with the binary: the .lock write refused and the notes
formatted in a -p run, the SessionStart text in the
transcript, the Stop hook's input; /hooks with the files;
on a pseudo-terminal, the Notification hook on a question, the warning
after the settings changed mid-session, /hooks reload.
Plugins
include/oklm/harness/plugins.h,
src/harness/plugins.c. A plugin is a directory installed
for the user (~/.config/oklm/plugins/NAME) or the project
(.oklm/plugins/NAME, the project's winning a name): a
manifest (.oklm-plugin/plugin.json or
.claude-plugin/plugin.json: name, version, description) and
any of commands/ (prompt commands,
/NAME:COMMAND), skills/
(NAME:SKILL), agents/
(NAME:AGENT), hooks/hooks.json (added to the
settings' hooks, ${OKLM_PLUGIN_ROOT} and
${CLAUDE_PLUGIN_ROOT} the plugin's directory) and
.mcp.json (its servers declared, scope plugin,
not asked again). Installed ones are on unless
enabledPlugins turns one off ({"NAME": false},
or an array of the only ones on).
oklm agent plugin list | install DIR|GIT-URL|NAME@MARKET [--scope user|project] | remove NAME | enable NAME | disable NAME | marketplace add NAME DIR|GIT-URL | marketplace list:
a marketplace is a directory or repository whose
marketplace.json lists plugins and their sources
(pluginMarketplaces in the user's settings).
/plugin (also /plugins) lists them in a
session; a change takes effect in the next one.
MCP servers
include/oklm/harness/mcp.h,
src/harness/mcp.c, over the JSON-RPC module (a message per
line) and the jobs (kind mcp).
- Configuration, the first scope declaring a name
wins: the files given with
--mcp-config FILE(several;--strict-mcp-configkeeps only them), the settings'mcpServers(local, project or user settings), the project's.mcp.json. A server is{"type": "stdio", "command": "...", "args": [...], "env": {...}}(stdio when no type and no url) or{"type": "http"|"sse", "url": "...", "headers": {...}};${VAR}and${VAR:-default}are expanded in the command, the arguments, the environment and the URL.deniedMcpServersandallowedMcpServers(names) filter them all. - Trust: a server of
.mcp.jsonis asked about once on a terminal (yes and no remembered in the local settings'enabledMcpjsonServersanddisabledMcpjsonServers, or once); without a terminal it is left out with a note until approved;enableAllProjectMcpServersapproves them all. - Streamable HTTP: an http server is a client of its
URL (TLS through nilorea): each message a POST accepting JSON or
server-sent events, the configuration's headers (an authorization) and
MCP-Protocol-Versionsent, theMcp-Session-Idthe initialize answer gives sent after; notifications answered 202; a watchdog cancels a call past its time; an error status is the call's error (HTTP 401: ...). The server's notifications and requests met within an answer's events are taken as on stdio; there is no GET stream for those it sends between requests, and an expired session (404) is not opened again. - OAuth (
include/oklm/harness/oauth.h,src/harness/oauth.c): a remote server that answers 401 is "needs auth" (/mcp, the start's line)./mcp login NAME(oroklm agent mcp login NAME) finds its authorization server from the protected resource metadata (the 401'sresource_metadata, else the well-known places, else the older default endpoints on the server itself), reads that server's metadata (RFC 8414, then OpenID's), registers a client (RFC 7591) unless"oauth": {"clientId": ..., "clientSecret": ..., "callbackPort": ..., "scope": ...}gives one, opens the browser on the authorization page (PKCE S256, a random state, theresourceindicator, the server's scope) and takes the code athttp://127.0.0.1:PORT/callbackwithin 5 minutes. Endpoints must be on https unless on this machine. The tokens go tomcp-credentials.jsonbeside the user's settings (OKLM_MCP_CREDENTIALSelsewhere), readable by the user alone, under the server's name and URL: a token is only sent to that URL, asAuthorization: Bearerunless the configuration sets its own. An expired token is refreshed before connecting; a refused one is refreshed and the request sent once more; a refused refresh means signing in again./mcp logout NAMEforgets the tokens. - Legacy SSE: a
"type": "sse"server's stream (GET, read by a thread of its own) first names the endpoint messages are POSTed to; each answer comes back as an event on the stream, matched to the request waiting; the stream is cut when the server is stopped. - Lifecycle: the stdio servers start as jobs outside
the commands' sandbox (configured and approved by the user like their
own programs, they often need the network and credentials), from the
main thread;
initialize(protocol 2025-06-18, roots and elicitation declared),notifications/initialized,tools/listwith its pages, and the resources and prompts counted, in parallel withinmcp.connectTimeoutMs(10 s). The start says how many connected and how many failed. Before each request the servers are looked after: one that died loses its tools and is reconnected after 1 s, doubled, five times at most;notifications/tools/list_changedlists its tools again; the prompt is rebuilt when the tools changed (not while background agents run). The servers' requests:roots/listanswers the project,pinganswers, elicitation is declined; sampling is not offered. - Tools:
mcp__SERVER__TOOL(characters a name may not hold replaced, 64 at most) with the server's input schema, its description prefixed(from the MCP server NAME), andsays it only readsfor areadOnlyHint(a hint, trusted for nothing). They go through the whole pipeline: schema check, hooks, permissions (mcp__SERVERallows all of a server's tools,mcp__SERVER__TOOLone,mcp__*all), audit. The result: text blocks as they are, images and audio named with their size, embedded resources' text, links; structured content as JSON when nothing else came;isErrormakes an error; cut pastmcp.maxOutputChars(100000, about 25000 tokens) with a note. A call waitsmcp.callTimeoutMs(120 s). Pastmcp.deferAboveTokensof definitions (by default a quarter of the context window: 8192 tokens with-c 32768, 2000 when the window is unknown), the MCP tools are deferred (mcp__*): each server's in a line of the prompt by their short names, called by their full names, their parameters loaded through ToolSearch. A small model does not search for tools: deferred, Qwen3-4B used the official filesystem server's tools in none of 9 runs (three wordings of that line), and in 3 of 3 with them shown. With--tool-rag Kevery MCP tool is deferred, the prompt gives each server's count, and the tools a message needs are retrieved and shown with it (agent-tools.md). - Resources:
ListMcpResources(every server's, or one's) andReadMcpResource(server and uri) while a server serves resources. The user names one in a message as@server:scheme://...: it is read (no question, the user asked) and given with the message, like@file. - Prompts: a server's prompts are typed as commands,
/mcp__SERVER__PROMPT arg ...: the words map to its arguments in order, the last one taking the rest of the line ("..."keeps blanks together); a required one missing is said; prompts/get's messages, joined, are sent as the request./mcplists them; they are not in the/menu (the registry has no removal for servers that come and go). /mcplists the servers (state, transport, scope, tools, resources, prompts, the definitions' size, or why one failed);/mcp tools|reconnect|enable|disable|log NAME./statuscounts them;/doctorwarns about failed ones.- Crashes told: a server that ended and one connected again are told before the next request, to the user (dimmed) and to the model (its tools changed), as is one that could not be reconnected.
- CLI:
oklm agent mcp add NAME [--scope local|project|user] [--transport stdio|http|sse] [--env K=V] [--header 'K: V'] -- COMMAND [ARGS](or the URL),add-json NAME JSON,remove NAME,list,get NAME(with the approval of a project server). - Interrupts: a stdio call interrupted by the user
returns at once, the server sent
notifications/cancelledwith the request's id (an HTTP call waits for its time limit). - Not yet: OAuth,
@completion of resources, cancellation of HTTP calls of a call on interrupt, sampling,oklm agent mcp serve.
On Qwen3-4B (OpenCL), asked to add 17 and 25 with the fake server's
add tool: it calls mcp__fake__add({"a":17,"b":25}) and
answers 42.