Skip to content

feat(clients): add AgentTools and the kosha-mcp MCP server (#584) - #601

Merged
decover-admin merged 11 commits into
mainfrom
devin/1795743945-agent-mcp
Nov 27, 2026
Merged

decover-admin merged 11 commits into
mainfrom
devin/1795743945-agent-mcp

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

What and why

Part of #584 (Phase L, #589): agents reach Kosha through tools shaped like the ones they already use, not the OpenSearch-shaped clients.

  • kosha_client.AgentTools (clients/python/kosha_client/agent.py): a thin SDK over the native /v1 API, one method per tool: search (BM25), semantic_search (kNN, or RRF hybrid with hybrid=True), filter, glob, read, count, aggregate, list_branches, branch, index_documents.
  • kosha-mcp (kosha_client/mcp_server.py, console script, new mcp extra pinned to mcp>=1.20,<2): serves those tools over stdio (default) or streamable HTTP (--transport http, /mcp).
  • glob ([agent] Path field and glob(): gitignore-style path matching and directory listing #585, merged in feat(filter): add a glob filter clause (#585) #599): a glob filter on the path field, sorted by path with _id as tie-breaker, so it lists like a filesystem and pages with next_search_after. Hits carry only id and path unless include_fields names more.
  • read ([agent] read(): line, page and byte ranges inside a document without fetching it whole #586, merged in feat(api): add read for line, page and byte ranges inside a document (#586) #600): POST /read by id or path, whole or start_line/end_line, page or byte_start/byte_end, with max_bytes. field defaults to body (AgentTools(text_field=...)), the field kosha-ingest writes.
  • Budgeted results: every hit is {"id", "score", "path"?, "fields", "truncated_fields"?, "highlight"?}. Hits per call are capped at 100, each stored string is cut to 500 chars and named in truncated_fields, and vectors are never returned. path is lifted out of the path field so agents can narrow with prefix or glob, then read the full text.
  • Scopes: by default only the 8 read tools are registered, all annotated readOnlyHint, so a read-scoped key is enough. branch and index_documents need --allow-writes.
  • Filter values: numbers inside term/terms/range/prefix are converted to strings, because models write {"range": {"year": {"gte": 2024}}} and the server rejects that with a 400.
  • API errors reach the agent as MCP tool errors that carry the server message, e.g. KoshaRequestError(400) [invalid_argument]: ... unknown filter clause.
  • Docs are in clients/python/README.md ("Agent tools and the MCP server"), with examples in clients/python/examples/ (Claude Desktop config, plain-Python script).

Not in this PR (follow-ups on #584):

How it was tested

  • tests/test_agent_tools.py: request bodies, result shaping and truncation, caps, field typing, filter normalization, glob sort/paging, read range bodies and validation errors.
  • tests/test_mcp_server.py: the tool list, read-only annotations, opt-in writes, and call_tool through to the API. CI and make client-python-test install .[mcp,ingest] so this file runs instead of being skipped.
  • Python client suite: 268 passed, 33 skipped.
  • By hand: a local kosha-server built from main (KOSHA_DATA_DIR, KOSHA_AUTH=disabled) driven by the official MCP client:
    • Over stdio with --allow-writes: index_documents, search, filter with prefix + sort, count with a numeric range, aggregate, branch, list_branches, and an invalid filter returning a tool error.
    • Over streamable HTTP: list_tools and count.
    • glob with **, case_insensitive and a two-page search_after walk; read by path with page, by id with lines and bytes; both again through call_tool.

Compatibility

  • The on-disk segment format (files under a segment, footer, posting/vector/filter layout)
  • The manifest, WAL, or Postgres schema
  • The /v1 wire contract (proto/kosha/v1/kosha.proto, request/response JSON)
  • None of the above

This is Python client only. mcp is an optional extra, so a plain pip install kosha-client still has no dependencies.

Checklist

  • cargo fmt --all -- --check (no Rust changes)
  • cargo clippy --all-targets --all-features -- -D warnings (no Rust changes)
  • cargo test --all-features (no Rust changes)
  • make client-python-test (if clients/python changed)
  • docker build -t kosha:ci . (if the Dockerfile or build configuration changed)
  • New KOSHA_* variables have a row in docs/configuration.md (none server-side; KOSHA_NAMESPACE is client-only, documented in the client README)
  • README / docs updated for user-visible changes

Link to Devin session: https://app.devin.ai/sessions/91ac22e94520430382b0941c2adf82e1
Open in Devin Desktop: https://app.devin.ai/desktop/session/91ac22e94520430382b0941c2adf82e1?variant=devin
Requested by: @ravi-decoverai


👀 2 findings for you to triage · Follow Devin's work

Devin Review

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

Co-Authored-By: Ravi Decover AI <[email protected]>

---kosha-bench---
microbenchmark: segment_memory (cargo bench -p kosha-query --bench segment_memory)
corpus: 8 segments × 4000 docs (32000 total), vocab ~20000
runner: Linux 6.6.141 x86_64 | rustc 1.100.0 (0ef1bc386 2026-11-09) | 2026-11-27T01:53:30Z

latency (v2 = current lazy format, median of inner samples):
  cold broad ("the")                 4.6 ms
  warm broad ("the")                 0.16 ms
  warm 2-term AND                    0.16 ms
  warm phrase                        0.12 ms
  warm wildcard w1*                  50.87 ms
---end kosha-bench---
@github-actions
github-actions Bot force-pushed the devin/1795743945-agent-mcp branch from f967846 to 17f620b Compare November 27, 2026 01:53
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

kNN microbench — main vs this PR (knn_open_search)

✅ No kNN regression past its limit.

before = main 60dbc4fcd · after = PR 8325d11ac · same runner, runs interleaved (2× / 2×), best p50 of each side

metric before after Δ limit
warm kNN p50 0.40 ms 0.35 ms -11.8% +25%
p90 (not gated) 0.49 ms 0.42 ms -13.5%
p99 (not gated) 1.03 ms 0.70 ms -31.7%
warm hybrid p50 0.53 ms 0.37 ms -29.9% +25%
p90 (not gated) 0.80 ms 0.48 ms -40.6%
p99 (not gated) 1.07 ms 0.59 ms -45.5%
cold kNN p50 3.14 ms 2.58 ms -17.7% +40%
p90 (not gated) 3.70 ms 3.01 ms -18.5%
p99 (not gated) 3.99 ms 3.59 ms -10.2%
open all segments p50 1.23 ms 1.20 ms -2.7% +40%
p90 (not gated) 1.32 ms 1.37 ms +3.8%
p99 (not gated) 1.44 ms 1.49 ms +3.6%
postings probed / query 100.0 100.0 +0.0% +10%

corpus 8 segs × 4000 docs, dim 256, 64 clusters · latency fails only past both the % limit and an absolute floor · postings/query is deterministic · label perf-regression-accepted to accept an intended cost

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

⏱ Microbench — main vs this PR (segment_memory, v2 format)

before = merge-base 60dbc4fcd · after = PR head 8325d11ac · same runner, back to back

metric pctl before (main) after (PR) Δ
cold broad ("the") p50 4.28 ms 3.00 ms -30.0% 🟢
p90 4.59 ms 3.96 ms -13.7% 🟢
p99 4.83 ms 4.40 ms -8.8%
warm broad ("the") p50 0.099 ms 0.096 ms -2.9%
p90 0.124 ms 0.128 ms +3.5%
p99 0.165 ms 0.141 ms -14.7% 🟢
warm 2-term AND p50 0.115 ms 0.127 ms +9.8%
p90 0.145 ms 0.143 ms -0.9%
p99 0.158 ms 0.172 ms +8.8%
warm 3-term AND broad p50 0.160 ms 0.122 ms -23.7% 🟢
p90 0.169 ms 0.151 ms -10.8% 🟢
p99 0.188 ms 0.204 ms +8.9%
warm phrase p50 0.101 ms 0.082 ms -18.2% 🟢
p90 0.107 ms 0.101 ms -5.3%
p99 0.130 ms 0.137 ms +4.9%
warm wildcard w1* p50 48.1 ms 45.5 ms -5.3%
p90 59.0 ms 51.0 ms -13.6% 🟢
p99 71.4 ms 62.4 ms -12.6% 🟢
resident while open — 13.1 MiB 13.1 MiB +0.0%

corpus 8 segs × 4000 docs · cold n=25, warm n=200 · nearest-rank percentiles · deltas within ±10% are usually runner noise

devin-ai-integration Bot and others added 4 commits November 27, 2026 01:58
…ow-remote

Co-Authored-By: Ravi Decover AI <[email protected]>

---kosha-bench---
microbenchmark: segment_memory (cargo bench -p kosha-query --bench segment_memory)
corpus: 8 segments × 4000 docs (32000 total), vocab ~20000
runner: Linux 6.6.141 x86_64 | rustc 1.100.0 (0ef1bc386 2026-11-09) | 2026-11-27T02:00:50Z

latency (v2 = current lazy format, median of inner samples):
  cold broad ("the")                 2.8 ms
  warm broad ("the")                 0.10 ms
  warm 2-term AND                    0.11 ms
  warm phrase                        0.08 ms
  warm wildcard w1*                  41.92 ms
---end kosha-bench---
@github-actions
github-actions Bot force-pushed the devin/1795743945-agent-mcp branch from 87a1198 to b810e8d Compare November 27, 2026 02:00
…ler cursors

Co-Authored-By: Ravi Decover AI <[email protected]>

---kosha-bench---
microbenchmark: segment_memory (cargo bench -p kosha-query --bench segment_memory)
corpus: 8 segments × 4000 docs (32000 total), vocab ~20000
runner: Linux 6.6.141 x86_64 | rustc 1.100.0 (0ef1bc386 2026-11-09) | 2026-11-27T02:05:19Z

latency (v2 = current lazy format, median of inner samples):
  cold broad ("the")                 4.0 ms
  warm broad ("the")                 0.11 ms
  warm 2-term AND                    0.12 ms
  warm phrase                        0.09 ms
  warm wildcard w1*                  44.06 ms
---end kosha-bench---
@github-actions
github-actions Bot force-pushed the devin/1795743945-agent-mcp branch from 15d204e to eee30de Compare November 27, 2026 02:05

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 9 findings. Devin fixed 7 findings; 2 findings are left for you to triage below.

Fixed by Devin (7)
  • Full pages missing continuation cursors — Missing sort values now emit "" (the cursor the server compares equal to Missing) and _score uses the hit score; paged 7 docs with 4 missing dates asc and desc locally with no skips or repeats.
  • Explicit cursors repeat boundary hits — The _id tie-breaker is only appended when there is no cursor or the cursor carries the extra _id value, so a caller cursor of one value per key keeps its own sort.
  • Empty namespace-wide counts and aggregations — Confirmed count() returned 0 on a 7-doc namespace path; count/aggregate now send match_all when there is no query and no filter (verified 7 against a local server).
  • Non-neighbors in filtered semantic search — Non-hybrid semantic_search now puts the filter in knn.filter only; hybrid sends it in both. Verified locally: k=2 with a filter returns 2 neighbours, total 2, no vectorless doc.
  • Skipped filter results at tied boundaries — filter() appends an _id asc tie-breaker when sort lacks one; paging 7 docs with tied dates 2 at a time returned all 7 with no duplicates.
  • Unavailable filter pagination cursors — Same root cause as the tie-break: sort keys are always added to source_includes and a full page returns next_search_after built from the last hit's raw values.
  • Unauthenticated access to network-bound MCP — HTTP transport now refuses a non-loopback --host unless --allow-remote is passed; README says to only do that behind an authenticating proxy.

View findings in Devin Review · Follow Devin's work

Devin Review

Comment on lines +293 to +295
# A document without the field sorts as missing, which the
# cursor "" denotes.
value = stored.get(key, "")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Invalid cursors for nested sorts

When a page sorts by a nested field, _sort_values marks its value missing even when it exists. The server returns the parent field, not the nested sort key. Following the cursor can repeat the page or skip remaining matches.

Devin left this for you to triage: Sorting filter() by a nested field gives a cursor of "" so the next page can repeat or skip. The client can only rebuild sort values from stored fields; I recommend the search API return each hit's sort values (ES-style sort array) and have AgentTools pass those through, rather than parsing nested parents client-side.

Learn more

The engine stores a nested object under its parent field name and indexes the nested leaves separately for filtering and sorting. Nested sorting uses those leaves, but hit materialization returns the original stored fields. The cursor builder looks for the dotted key in those returned fields and emits the missing marker. Numeric cursor comparison treats every number as greater than that marker, so the document ID cannot restore the page boundary.

Example: Filter for documents with author.age, sort by author.age ascending, and request one hit. If d1 has age 30 and d2 has age 40, the first page returns d1 and emits ["", "d1"]. Following that cursor returns d1 again instead of d2.

Recommended fix: Prefer returning the engine’s actual sort values with each hit and using them for cursors. If the fix must remain client-only, retrieve the parent field even when projecting fields, apply the server’s nested sort rules, and avoid advertising a cursor when the sort value cannot be reconstructed. Add an ascending and descending round-trip test.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +293 to +295
# A document without the field sorts as missing, which the
# cursor "" denotes.
value = stored.get(key, "")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Missing sort values hide empty keywords

When an ascending keyword page ends on a missing value, _sort_values gives it the same cursor as an empty keyword. The server compares both as equal, so it skips empty-keyword matches with smaller IDs.

Devin left this for you to triage: The string cursor cannot distinguish a missing keyword from an empty one (the server compares both equal to ""), so an ascending page ending on a missing value can skip empty-keyword docs with smaller ids. Same fix as the nested-sort finding: return per-hit sort values from the server, ideally with a distinct missing marker.

Learn more

The segment writer indexes empty keyword strings as ordinary values. Sort ordering puts missing values before all text, including the empty string. Cursor comparison instead treats an empty cursor component as equal to both a missing value and empty text. It then compares document IDs, even though these documents were not tied in the original ordering.

Example: Sort by label ascending with one hit per page. Document z has no label and document a has label="". The first page returns z and emits ["", "z"]. The next request discards a because a sorts before z by ID, even though the original result order places a after z.

Recommended fix: Add a cursor representation that distinguishes missing values from empty text, and compare those components using the same ordering as the initial request. Until the wire format can express that boundary, avoid returning an ambiguous continuation and document the limitation. Test pagination across a missing keyword and an empty keyword with inverse ID order.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

…t-mcp

Co-Authored-By: Ravi Decover AI <[email protected]>

# Conflicts:
#	.github/workflows/ci.yml
#	Makefile
#	clients/python/README.md
#	clients/python/pyproject.toml

---kosha-bench---
microbenchmark: segment_memory (cargo bench -p kosha-query --bench segment_memory)
corpus: 8 segments × 4000 docs (32000 total), vocab ~20000
runner: Linux 6.6.141 x86_64 | rustc 1.100.0 (0ef1bc386 2026-11-09) | 2026-11-27T08:35:16Z

latency (v2 = current lazy format, median of inner samples):
  cold broad ("the")                 3.2 ms
  warm broad ("the")                 0.11 ms
  warm 2-term AND                    0.12 ms
  warm phrase                        0.09 ms
  warm wildcard w1*                  43.44 ms
---end kosha-bench---
@github-actions
github-actions Bot force-pushed the devin/1795743945-agent-mcp branch from f5de83b to 945630c Compare November 27, 2026 08:35
Co-Authored-By: Ravi Decover AI <[email protected]>

---kosha-bench---
microbenchmark: segment_memory (cargo bench -p kosha-query --bench segment_memory)
corpus: 8 segments × 4000 docs (32000 total), vocab ~20000
runner: Linux 6.8.0-1060-aws x86_64 | rustc 1.99.1 (58cf8f9c3 2026-10-13) | 2026-11-27T19:13:02Z

latency (v2 = current lazy format, median of inner samples):
  cold broad ("the")                 3.9 ms
  warm broad ("the")                 0.36 ms
  warm 2-term AND                    0.76 ms
  warm phrase                        0.28 ms
  warm wildcard w1*                  89.30 ms
---end kosha-bench---
Co-Authored-By: Ravi Decover AI <[email protected]>

---kosha-bench---
microbenchmark: segment_memory (cargo bench -p kosha-query --bench segment_memory)
corpus: 8 segments × 4000 docs (32000 total), vocab ~20000
runner: Linux 6.8.0-1060-aws x86_64 | rustc 1.99.1 (58cf8f9c3 2026-10-13) | 2026-11-27T19:16:26Z

latency (v2 = current lazy format, median of inner samples):
  cold broad ("the")                 5.7 ms
  warm broad ("the")                 0.32 ms
  warm 2-term AND                    0.55 ms
  warm phrase                        0.54 ms
  warm wildcard w1*                  118.77 ms
---end kosha-bench---

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 2 findings. All 2 findings are left for you to triage in Devin Review.

View findings in Devin Review · Follow Devin's work

Devin Review

@decover-admin
decover-admin merged commit d8254ef into main Nov 27, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants