The Kibi Model Context Protocol (MCP) server is the primary interface for LLM agents. The server operates over stdio and receives JSON-RPC 2.0 requests.
The public MCP surface is intentionally curated. Agents can call exact lookup, discovery/reporting, mutation, and validation tools through MCP.
The canonical MCP names in this reference use the kb_* form. Some hosts display tools with the configured MCP server name prefixed. In OpenCode, the same tools commonly appear as kibi_kb_search, kibi_kb_query, kibi_kb_upsert, kibi_kb_check, and kibi_kb_autopilot_generate. Use the host-visible prefixed name when an agent must reference an exact tool identifier; the semantics are identical to the canonical kb_* names documented here.
Discover existing repository entities and bootstrap the KB via read-only candidate synthesis. Use this as the backend for the interactive /init-kibi onboarding workflow.
Parameters:
includeGenericMarkdown(optional): Include generic Markdown content as candidate evidence.minConfidence(optional): Minimum confidence threshold for generated candidates.maxCandidates(optional): Maximum number of candidates to return.entityTypes(optional): Limit generation to selected entity types.bootstrapContext(optional): Declared project summary, source-of-truth paths/notes, priority roots, and verification anchors.
Returns:
Grouped candidate entities synthesized from declared context and codebase evidence, plus structuredContent.applyPlan: the exact sequential kb_upsert payloads for those candidates. Candidates must be explicitly previewed and approved by the user before applying the plan.
During read-only discovery (for example kb_autopilot_generate) and other file-based inference, Kibi will exclude files and directories matched by the repository ignore policy:
- repository root
.gitignorefiles and nested.gitignorefiles in subdirectories .git/info/exclude
In addition to these repository-configured ignores, Kibi hard-denies a set of common tool/runtime directories that are never inspected for candidates:
.sisyphus/**.opencode/**.kb/**.git/**node_modules/**vendor/**third_party/**
Notes and migration limitations:
- Global Git excludes (for example
~/.config/git/ignore) are not read or honored. - When MCP tools return a non-null migration warning, run
kibi migrate --dry-run, thenkibi migrate --yesbefore relying on strict checks or automated writes. - Symbol granularity migration marks existing coarse file/module links as
legacy-link; new MCPkb_upsertcalls must target the narrow behavioral symbol when one exists, or provide an explicitgranularity_reason. Interfaces, type aliases, and enums aretype-shapesymbols and do not by themselves block a coarse behavioral link.
When using discovery tools, agents and operators should assume that ignored paths are not considered as evidence for candidate entities and that any candidates requiring approval will come from non-ignored sources only.
When prose contains a machine-checkable rule, do not store it only in text_ref or freeform links. Use the concise decision tree in docs/modeling-cheatsheet.md.
- Call
kb_semantic_advisorwhen starting from raw prose, or runkb_validate_upsertbeforekb_upsertfor new or updated normative requirements. Both return semantic advisor receipts when prose appears machine-checkable but unmodeled. - For property/value requirements, call
kb_model_requirementor create afact_kind: subjectfact plus afact_kind: property_valuefact. Link the requirement withconstrainsandrequires_property. - For ontology claims, call
kb_suggest_predicatesbefore writing prose. Apply the returnedfact_kind: predicateplan and link withrequires_predicate, or record the returnedreview:ontology-gapobservation. - Use snake_case field names exactly as the MCP schema shows.
kb_upsert.propertiesrejects camelCase aliases such assubjectKey,propertyKey,predicateName, and genericvalue.
Semantic advisor receipts are advisory in v1. They identify likely modeling debt; they do not prove prose contradictions, they do not auto-create facts, and they do not replace strict constrains/requires_property or requires_predicate links. If a receipt reports logic_readiness: needs_modeling, inspect suggestions: high-confidence strict-property and predicate suggestions include draft applyPlan payloads, ambiguous prose emits an ambiguity observation plan, and unsupported logical prose emits an ontology-gap observation with a recommended predicate schema. Review and apply the suggested modeling tool or observation before treating the requirement as Prolog-checkable.
Model a normative requirement claim into a deterministic strict write-set for contradiction-ready KB persistence. Accepts an LLM-supplied semantic claim (or falls back to heuristic extraction from a plain statement) and returns a ready-to-apply plan of req + fact entities with typed constrains/requires_property relationships.
High-confidence claims (≥ 0.7) produce a strict write-set: one req, one fact_kind: subject, one fact_kind: property_value, and two typed relationships. Low-confidence claims (< 0.7) produce a single fact_kind: observation artifact that does not enter the contradiction lane, plus a warning explaining how to retry with explicit claim fields.
Parameters:
statement(required): Plain-language normative statement to modelclaim(optional): ExplicitSemanticClaimobject withsubjectKey,propertyKey,operator,value,confidence, andsourceReffields. When provided, heuristic extraction is skipped.
Returns:
A writeSet discriminated union:
isStrict: true— includesreq,subjectFact,propertyFact,relationships, and anapplyPlanready for sequentialkb_upsertcalls.isStrict: false— includes a singleobservationFactfor non-normative or low-confidence input.
Also returns migrationWarning (non-null when the workspace KB schema is outdated) and schemaVersionStatus for pre-flight awareness.
Human approval is not required. The write-set is deterministic and idempotent — the same claim always produces the same stable entity IDs (SHA-256 of normalized source/subject/property/operator/value). Apply via sequential kb_upsert calls at any time.
Suggest ontology predicate candidates for a prose requirement before an agent writes freeform ontology notes. Agents should spell out the requirement claim, call this tool, then either apply a returned fact_kind: predicate plan linked with requires_predicate or record the returned review:ontology-gap observation when no predicate fits.
The tool ranks project-local fact_kind: predicate_schema facts when available and falls back to Kibi's built-in predicate catalog covering state, transitions, guards, exceptions, mutual exclusion, dependencies, ownership, retry policies, escalation rules, availability SLAs, notification routing, idempotency, data residency, audit logging, consent, lifecycle actions, conflict resolution, fallback behavior, batch operations, consistency rules, build constraints, environment safety rules, schema invariants, coding standards, migration boundaries, absence/removal requirements, offline behavior, release gates, platform consistency, preservation rules, abstraction boundaries, security configuration, ordered strategies, refresh policies, scoped authorization, documentation standards, warmup policies, visual layout rules, enforcement-location rules, reconciliation rules, throttling policies, persistence/save/discard behavior, accessibility, retention, resource constraints, feature gates, events, permissions, defaults, uniqueness, state memberships, temporal ordering, conditional behavior, rate limits, and acceptance outcomes. Built-in candidates include usage hints (use_when / do_not_use_when) so agents can choose precise predicates instead of matching keywords blindly.
Parameters:
text(required): Prose requirement or claim to classify into ontology predicates.requirementId(optional): Existing requirement ID. When present, the response includes arelationshipPlandescribing therequires_predicatelink to attach after preserving existing requirement metadata.source(optional): Provenance/text reference for generated predicate facts or ontology-gap observations.subjectHint(optional): Canonical subject key to use as the first predicate argument.maxCandidates(optional): Maximum ranked predicate candidates to return.minScore(optional): Minimum candidate score; higher values make ontology-gap fallback more likely.includeExistingSchemas(optional): Include project-local predicate schema facts alongside built-ins.
Returns:
candidates: Ranked predicate suggestions with schema signature, usage hints, orderedpredicate_args,canonical_key, score, and rationale.recommendedAction:apply_requires_predicatewhen a candidate fits, otherwiserecord_ontology_gap.structuredContent.applyPlan: A ready-to-applykb_upsertpayload for the top predicate fact, or an explicitfact_kind: observationtaggedreview:ontology-gapandneeds_schema_extension.structuredContent.relationshipPlan: WhenrequirementIdis supplied and a predicate fits, the req -> factrequires_predicatelink to attach after querying/preserving the existing requirement entity. This is separate fromapplyPlanso the tool never emits a foreign-source relationship thatkb_upsertwould reject.
Example:
{
"text": "When the user navigates away with unsaved annotation edits, the editor must auto-save the draft and return to idle mode.",
"requirementId": "REQ-EDITOR-004",
"source": "requirements/editor.md#L12",
"subjectHint": "editor.annotation"
}Analyze requirement prose without mutating the KB. Use this before constructing a kb_upsert payload when you have raw requirement text and want modeling suggestions.
Parameters:
text(required): Requirement prose to inspect.type(optional): Entity type context. Currentlyreqis supported.id(optional): Requirement ID used for draft relationship guidance.title(optional): Requirement title for draft apply plans.source(optional): Provenance for draft suggestions.status(optional): Requirement status for draft suggestions.
Returns:
structuredContent.receipt: Semantic advisor receipt with detected signals, ambiguity witnesses, modeling suggestions, candidate lane, payload hash, and suggested next tools.structuredContent.warnings: Non-blocking warning strings explaining why the prose is not yet contradiction-checkable.
Suggestion kinds include strict_property, predicate, ambiguity_observation, and ontology_gap. Supported deterministic suggestions include multi-claim prose, cardinality, thresholds with units, retention/expiry durations, booleans, enum sets, permissions and prohibitions, defaults, uniqueness constraints, state memberships, state transitions, exception rules, mutual exclusion, dependency rules, ownership, retry policies, escalation rules, availability SLAs, notification routing, idempotency rules, data residency rules, audit logging, consent requirements, lifecycle archive/delete/expiry rules, conflict-resolution strategies, fallback/degradation behavior, batch operation constraints, cross-entity consistency/reference requirements, conditional behavior, temporal ordering, comparative numeric constraints, rate limits, and ambiguity observations.
For exact predicate suggestions, the receipt candidate_lane and suggested_next_tools follow the generated suggestion rather than the weaker signal heuristic. For example, a lifecycle rule containing a number still routes to kb_suggest_predicates, not kb_model_requirement, when the advisor can ground it as a predicate fact.
Retrieve entities by type, id, tags, or sourceFile. Supports limit and offset pagination.
Parameters:
type(optional): Entity type (req,scenario,test,adr,flag,event,symbol,fact)id(optional): Entity ID (exact match)tags(optional): Tag list for filteringsourceFile(optional): Source-file substring filterlimit(optional): Maximum number of resultsoffset(optional): Number of results to skip
Returns: Array of matching entities with deterministic ordering.
Example:
{
"type": "req",
"sourceFile": "src/auth/login.ts",
"limit": 20
}Search entities by metadata and markdown body text for exploratory discovery.
Parameters:
query(required): Free-text querytype(optional): Entity type filterlimit(optional): Maximum number of ranked resultsoffset(optional): Number of results to skip
Returns: Ranked results with match reasons and optional snippets.
Example:
{
"query": "login flow",
"type": "req",
"limit": 10
}Return branch, snapshot, and freshness metadata for the attached KB.
Returns: Branch name, snapshot ID, sync state, dirty flag, and KB path metadata.
Example:
{}MK|### kb_skills_list
XZ|
PW|List bundled Kibi agent skills available for progressive disclosure. Read-only; does not mutate the KB or require Prolog.
QW|
RH|Parameters:
ZJ|- None
QW|
KQ|Returns:
JP|Array of skill manifests with id, name, version, description, and declared resources.
MS|
TH|Example:
YP|json TT|{} TV|
NJ|
BN|### kb_skills_load
HT|
YK|Load a bundled Kibi agent skill by ID, returning its manifest metadata, Markdown body, declared resources, content hash, and source type. Read-only; does not execute scripts or require Prolog.
YQ|
RH|Parameters:
ZV|- id (required): Bundled skill ID to load. Example: 'kibi-usage'.
XY|
KQ|Returns:
SB|Skill bundle with manifest, body, resources, hash, and sourceType.
BQ|
TH|Example:
YP|json TY|{ RN| "id": "kibi-usage" MJ|} HP|
SH|
WV|### kb_skills_read
VH|
YX|Read a declared resource from a bundled Kibi agent skill. Resource paths are restricted to the skill manifest; arbitrary file paths are not exposed. Read-only; does not require Prolog.
PX|
RH|Parameters:
VZ|- id (required): Bundled skill ID. Example: 'kibi-usage'.
KQ|- resource (required): Manifest-declared resource path to read. Example: 'resources/fact-lanes.md'.
YY|
KQ|Returns:
VZ|Resource contents as text.
BM|
TH|Example:
YP|```json
TT|{
TV| "id": "kibi-usage",
BQ| "resource": "resources/fact-lanes.md"
SZ|}
YN|
Run curated missing/present relationship analysis over KB entities.
Parameters:
type(optional): Entity type filtermissingRelationships(optional): Required-to-be-absent relationship typespresentRelationships(optional): Required-to-be-present relationship typestags(optional): Tag filtersourceFile(optional): Source-file substring filterlimit/offset(optional): Pagination controls
Returns: Matching rows, relationship counts, and status metadata.
Example:
{
"type": "req",
"missingRelationships": ["specified_by", "verified_by"],
"sourceFile": "src/auth"
}Generate curated coverage reports.
Parameters:
by(optional):req,symbol, ortypetags(optional): Tag filterincludePassing(optional): Include fully covered rows in report contexts that support itincludeTransitive(optional): Include transitive symbol coveragelimit/offset(optional): Pagination controls
Returns: Coverage summary rows and status metadata.
For requirement coverage, summaries distinguish evaluated must-priority requirements from rows marked notApplicable.
Example:
{
"by": "req",
"includePassing": false,
"includeTransitive": true
}Run bounded graph traversal from one or more seed IDs.
Parameters:
seedIds(required): Starting IDsrelationships(optional): Relationship filterdirection(optional):outgoing,incoming, orbothdepth(optional): Maximum traversal depthentityTypes(optional): Filter returned nodes by typemaxNodes/maxEdges(optional): Traversal bounds
Returns: Nodes, edges, truncation flag, and status metadata.
Example:
{
"seedIds": ["REQ-001"],
"direction": "both",
"depth": 2,
"maxNodes": 100,
"maxEdges": 200
}Run an opt-in SPARQL SELECT query against an external HTTP(S) SPARQL endpoint. This tool is remote-only: it does not query Kibi's local RDF store directly, does not start a local SPARQL endpoint, and does not store credentials.
Parameters:
endpoint(required): Remote SPARQL endpoint URL. Must start withhttp://orhttps://; local file paths are rejected.query(required): SPARQLSELECTquery text.timeoutMs(optional): Positive timeout in milliseconds for the remote request.
Returns: Rows returned by the remote endpoint, serialized as structured MCP content. Network availability, endpoint rate limits, and remote endpoint authentication requirements are outside Kibi's control.
Example:
{
"endpoint": "https://query.wikidata.org/sparql",
"query": "SELECT ?item WHERE { ?item wdt:P31 wd:Q146 . } LIMIT 5",
"timeoutMs": 15000
}Kibi's Prolog core may use maintained SWI-Prolog libraries such as library(aggregate) for count/reporting helpers and library(chr) for isolated derived-fact pilots. These are internal implementation details and do not change public KB semantics, MCP response shapes, or the canonical validation rules unless a future release explicitly documents such a change.
Create or update a single entity and optional relationships in one call.
Parameters:
type: Entity type enumid: Entity IDproperties: Entity fields, including requiredtitleandstatus(status values depend on entity type; legacy values may still be accepted for compatibility). Forsymbolentities this may includesourceFile,symbol_role, andgranularity_reason; forfactentities this includes typed fact fields such asfact_kind,subject_key,property_key,operator,value_type, and one matchingvalue_*field.relationships(optional): Relationship rows with enum-backedtype,from, andto
symbol_role values are behavioral, structural, type-shape, config, module, and unknown. Use behavioral for manual anchors when behavior is hidden inside factory/expression composition and the extractor cannot create a narrower symbol.
Returns:
Confirmation of entity creation/update and relationship creation counts. Successful responses may also include structuredContent.semanticAdvisor and structuredContent.warnings. The advisor receipt can contain draft strict-property, predicate, ambiguity-observation, or ontology-gap suggestions with apply plans. These suggestions are non-blocking in v1, but agents should review and repair them before considering prose-heavy requirements contradiction-checkable.
Validate a kb_upsert payload without mutating the KB. This read-only preflight returns valid, errors, warnings, semanticAdvisor, and normalizedPreview so agents can fix schema issues and semantic modeling gaps before calling kb_upsert.
semanticAdvisor includes a version, payload hash, logic readiness, candidate lane, detected signals, ambiguity witnesses, modeling suggestions, and suggested next tools. Use the receipt as proof that the payload was inspected, not as proof that the prose is logically enforced.
Delete one or more entities by ID. Deletion is blocked when dependents still reference the target.
Parameters:
ids: Array of entity IDs to delete
Returns: Confirmation of deletion, or an error describing blocked dependents.
Run KB validation rules after mutations.
Parameters:
rules(optional): Validation rule subset (must-priority-coverage,symbol-coverage,symbol-traceability,no-dangling-refs,no-cycles,required-fields,deprecated-adr-no-successor,domain-contradictions,strict-fact-shape,strict-req-fact-pairing). Note:strict-fact-shapeandstrict-req-fact-pairingare migration checks and are disabled by default.domain-contradictionsapplies only to strict-lane facts.
Returns: Validation report with any violations found and suggested fixes.
- MCP clients discover available tools through
tools/list. - MCP clients discover available prompts through
prompts/listandprompts/get. - Allowed static values are encoded directly in each tool's
inputSchemaenums. - There are no separate runtime listing tools for entity or relationship types.
Interactive onboarding workflow for day-0 KB activation. It guides agents to ask at most 4 bounded questions to gather declared context, call kb_autopilot_generate for read-only synthesis, present a preview for user approval, and perform sequential kb_upsert followed by kb_check.
- The server attaches to the active git branch automatically at startup.
- If the active branch KB does not exist, the server copies from the previously active branch KB when available; otherwise it creates an empty branch KB.
- Branch KBs are revalidated and updated automatically on branch change—no server restart is required for normal branch operations.
- You can override the branch selection by setting the
KIBI_BRANCHenvironment variable before starting the server. - Branch garbage collection is not part of the public MCP interface. Use
kibi gcor automation hooks instead.
For same-branch workflows, MCP validates the attached branch KB against filesystem stat metadata before attach-sensitive operations. When MCP detects a KB replacement for the same branch, it triggers a controlled re-attach flow.
- The session stores an
attachedBranchStampat attachment time. - MCP recomputes the latest branch stamp with
readBranchKbStampand compares it withsameBranchKbStamp. - If stale, MCP runs a full
refreshAttachedBranchKbattempt. - For transient refresh failures, MCP retries through
refreshAttachedBranchKbWithRetry. - If recovery fails, MCP returns a
KbRefreshErrorand the operation fails closed.
This behavior is important after external branch operations such as kibi sync --rebuild, where the branch KB snapshot can be replaced while the MCP process stays running.
- Interactive Bootstrap: Start with the
/init-kibiworkflow to gather declared context and synthesize entities. Always preview candidates for user approval before applying. - Gather Context: Use
kb_searchfor discovery (decomposing broad tasks into focused probes) andkb_queryfor exact follow-up. - Gather Context: Use
kb_searchfor discovery (decomposing broad tasks into focused probes) andkb_queryfor exact follow-up. - Inspect Freshness: Use
kb_statuswhen branch or stale-state confidence matters. - Analyze: Use
kb_find_gaps,kb_coverage, andkb_graphfor curated reporting. - Execute Changes: Use
kb_upsertto create/update entities and relationships. - Validate: Run
kb_checkafter structural changes. - Clean Up: Use
kb_deleteonly for intentional removals after validating dependencies.
Modeling note: Use flag for runtime/config gates. Bug and workaround notes belong in fact entities, usually with fact_kind: observation or meta. Strict facts drive contradiction checks; observation/meta are non-blocking notes.
The MCP server returns structured errors for:
- Invalid parameters (missing required fields, invalid enum values)
- Referential integrity violations (attempting to delete entities with dependents)
- Branch KB startup/attach failures
- Validation failures
Always check error responses before proceeding with more mutations. For common validation failures and recovery payloads, see docs/error-reference.md. In particular, strict fact writes must use subject_key, property_key, value_type, and exactly one typed value_* field; do not use subjectKey, propertyKey, or generic value in kb_upsert.properties.
- Query results are sorted and de-duplicated for consistency
- MCP responses use explicit field names and fixed shapes
- Validation output is stable across repeated runs on unchanged KB state