Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(retrieval): inline matched content on demand (#4261)

Jiahui Zhou5a154317cdb1
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 9a21d0027..16d38b037 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -642,6 +642,7 @@ impl HttpClient {
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
tags: Option<Vec<String>>,
+ read_content: bool,
) -> Result<serde_json::Value> {
let image_url = normalize_image_input(image)?;
let mut body = serde_json::json!({
@@ -656,6 +657,7 @@ impl HttpClient {
"level": level,
"context_type": context_type,
"tags": tags,
+ "read_content": read_content.then_some(true),
});
compact_request_body(&mut body);
self.post("/api/v1/search/find", &body).await
@@ -675,6 +677,7 @@ impl HttpClient {
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
tags: Option<Vec<String>>,
+ read_content: bool,
) -> Result<serde_json::Value> {
let image_url = normalize_image_input(image)?;
let mut body = serde_json::json!({
@@ -690,6 +693,7 @@ impl HttpClient {
"level": level,
"context_type": context_type,
"tags": tags,
+ "read_content": read_content.then_some(true),
});
compact_request_body(&mut body);
self.post("/api/v1/search/search", &body).await
diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rs
index aa720dfaa..632fbd6aa 100644
--- a/crates/ov_cli/src/commands/search.rs
+++ b/crates/ov_cli/src/commands/search.rs
@@ -129,6 +129,7 @@ pub async fn find(
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
tags: Option<Vec<String>>,
+ read_content: bool,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
@@ -145,6 +146,7 @@ pub async fn find(
level,
context_type,
tags,
+ read_content,
)
.await?;
output_search_results(
@@ -170,6 +172,7 @@ pub async fn search(
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
tags: Option<Vec<String>>,
+ read_content: bool,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
@@ -187,6 +190,7 @@ pub async fn search(
level,
context_type,
tags,
+ read_content,
)
.await?;
output_search_results(
@@ -452,6 +456,18 @@ fn render_search_result_card(
lines.push(format!("{SEARCH_INDENT}{}", theme::body(line)));
}
}
+
+ if let Some(content) = object
+ .and_then(|object| object.get("content"))
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|content| !content.is_empty())
+ {
+ lines.push(String::new());
+ for line in content.lines() {
+ lines.push(format!("{SEARCH_INDENT}{}", theme::body(line)));
+ }
+ }
}
fn render_skill_name_and_description(
@@ -802,6 +818,25 @@ mod tests {
}
}
+ #[test]
+ fn search_result_cards_show_full_inlined_content_after_the_abstract() {
+ let results = json!([
+ {
+ "context_type": "resource",
+ "uri": "viking://resources/deploy.md",
+ "abstract": "Deployment summary.",
+ "content": "# Deploy\n\nStep one.\nStep two.\nStep three."
+ }
+ ]);
+
+ let rendered = strip_ansi(&render_search_results_for_table(&results).expect("cards"));
+
+ assert!(rendered.contains("Deployment summary."));
+ for line in ["# Deploy", "Step one.", "Step two.", "Step three."] {
+ assert!(rendered.contains(line), "missing inlined content line: {line}");
+ }
+ }
+
#[test]
fn search_result_cards_handle_missing_optional_fields() {
let results = json!([
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index a2341f098..d5ac097f3 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -1393,6 +1393,7 @@ pub async fn handle_find(
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
tags: Option<Vec<String>>,
+ read_content: bool,
ctx: CliContext,
) -> Result<()> {
let query = query.unwrap_or_default();
@@ -1424,6 +1425,9 @@ pub async fn handle_find(
if let Some(ref t) = tags {
params.push(format!("--tags {}", t.join(",")));
}
+ if read_content {
+ params.push("--read-content".to_string());
+ }
params.push(format!("\"{}\"", query));
print_command_echo("ov find", &params.join(" "), ctx.config.echo_command);
let client = ctx.get_client();
@@ -1440,6 +1444,7 @@ pub async fn handle_find(
level,
context_type,
tags,
+ read_content,
ctx.output_format,
ctx.compact,
)
@@ -1458,6 +1463,7 @@ pub async fn handle_search(
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
tags: Option<Vec<String>>,
+ read_content: bool,
ctx: CliContext,
) -> Result<()> {
let query = query.unwrap_or_default();
@@ -1492,6 +1498,9 @@ pub async fn handle_search(
if let Some(ref t) = tags {
params.push(format!("--tags {}", t.join(",")));
}
+ if read_content {
+ params.push("--read-content".to_string());
+ }
params.push(format!("\"{}\"", query));
print_command_echo("ov search", &params.join(" "), ctx.config.echo_command);
let client = ctx.get_client();
@@ -1509,6 +1518,7 @@ pub async fn handle_search(
level,
context_type,
tags,
+ read_content,
ctx.output_format,
ctx.compact,
)
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 152935a68..7aa6ff826 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -752,6 +752,9 @@ enum Commands {
/// Only include results matching all of these explicit tags
#[arg(long = "tags", value_delimiter = ',')]
tags: Option<Vec<String>>,
+ /// Include the full visible content for every matched URI
+ #[arg(long, help_heading = "Advanced options")]
+ read_content: bool,
},
/// [Experimental][Data] Run context-aware retrieval
Search {
@@ -821,6 +824,9 @@ enum Commands {
/// Only include results matching all of these explicit tags
#[arg(long = "tags", value_delimiter = ',')]
tags: Option<Vec<String>>,
+ /// Include the full visible content for every matched URI
+ #[arg(long, help_heading = "Advanced options")]
+ read_content: bool,
},
/// [Data] Run content pattern search
Grep {
@@ -3526,6 +3532,7 @@ async fn main() {
level,
context_type,
tags,
+ read_content,
} => {
handlers::handle_find(
query,
@@ -3538,6 +3545,7 @@ async fn main() {
level,
context_type,
tags,
+ read_content,
ctx,
)
.await
@@ -3554,6 +3562,7 @@ async fn main() {
level,
context_type,
tags,
+ read_content,
} => {
handlers::handle_search(
query,
@@ -3567,6 +3576,7 @@ async fn main() {
level,
context_type,
tags,
+ read_content,
ctx,
)
.await
diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.md
index c3cfc7bec..f48b95ae5 100644
--- a/docs/en/api/06-retrieval.md
+++ b/docs/en/api/06-retrieval.md
@@ -67,6 +67,7 @@ The `find()` method performs pure vector similarity search for simple query scen
| time_field | "updated_at" \| "created_at" | No | "updated_at" | Metadata time field used by `since` / `until` |
| level | str | No | None | Limit results to specific level(s), e.g., `0`, `1`, `2`, or `0,1,2`. CLI `--level`/`-L` maps to this field |
| include_provenance | bool | No | False | Include provenance/query-plan details in serialized result |
+| read_content | bool | No | False | Read each final matched URI with the visible-content read semantics and inline the result as `content`. Individual read failures leave the hit unchanged. |
| telemetry | bool \| object | No | False | Attach telemetry data to response |
**Target resolution notes**:
@@ -81,6 +82,8 @@ The `find()` method performs pure vector similarity search for simple query scen
**FindResult Structure**
+When `read_content=true`, each successfully read hit additionally contains `content`. This is a full file read, so use `limit` to bound response size. `search(mode="context")` rejects `read_content` because context assembly already enforces its own token budget.
+
```python
class FindResult:
memories: List[MatchedContext] # Memory contexts
@@ -402,6 +405,7 @@ The `search()` method adds session context understanding and intent analysis cap
| time_field | "updated_at" \| "created_at" | No | "updated_at" | Metadata time field used by `since` / `until` |
| level | str | No | None | Limit results to specific level(s), e.g., `0`, `1`, `2`, or `0,1,2`. CLI `--level`/`-L` maps to this field |
| include_provenance | bool | No | False | Include provenance/query-plan details in serialized result |
+| read_content | bool | No | False | Read each final matched URI with the visible-content read semantics and inline the result as `content`. Individual read failures leave the hit unchanged. Only supported by `mode="list"`. |
| telemetry | bool \| object | No | False | Attach telemetry data to response |
`search()` uses the same target resolution and explicit tag filtering rules as `find()`, including the peer collection filter selected by `X-OpenViking-Actor-Peer` or SDK `actor_peer_id`. When `image_url` is provided, `search()` uses direct image retrieval and skips session query planning.
diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.md
index 38d4f87ca..9ab0a68bf 100644
--- a/docs/zh/api/06-retrieval.md
+++ b/docs/zh/api/06-retrieval.md
@@ -68,6 +68,7 @@ OpenViking 提供多种检索方法,包括简单的向量相似度搜索、带
| time_field | "updated_at" \| "created_at" | 否 | "updated_at" | since/until 使用的元数据时间字段 |
| level | str | 否 | None | 限定结果的层级范围,例如 `0`、`1`、`2` 或 `0,1,2`。CLI `--level`/`-L` 会映射到这个字段 |
| include_provenance | bool | 否 | False | 在序列化结果中附带 provenance / query-plan 细节 |
+| read_content | bool | 否 | False | 按可见内容 read 语义读取每个最终命中的 URI,并以内联 `content` 返回。单个读取失败时保留原命中,不附加内容。 |
| telemetry | bool \| object | 否 | False | 在响应中附带遥测数据 |
**目标解析说明**:
@@ -82,6 +83,8 @@ OpenViking 提供多种检索方法,包括简单的向量相似度搜索、带
**FindResult 结构**
+设置 `read_content=true` 后,每个成功读取的命中都会额外包含 `content`。这是完整文件读取,请用 `limit` 控制响应大小。`search(mode="context")` 会拒绝该参数,因为 context 组装已有自己的 token 预算。
+
```python
class FindResult:
memories: List[MatchedContext] # 记忆上下文
@@ -404,6 +407,7 @@ openviking find "红色海报风格" --image ./poster.png --uri "viking://resour
| time_field | "updated_at" \| "created_at" | 否 | "updated_at" | since/until 使用的元数据时间字段 |
| level | str | 否 | None | 限定结果的层级范围,例如 `0`、`1`、`2` 或 `0,1,2`。CLI `--level`/`-L` 会映射到这个字段 |
| include_provenance | bool | 否 | False | 在序列化结果中附带 provenance / query-plan 细节 |
+| read_content | bool | 否 | False | 按可见内容 read 语义读取每个最终命中的 URI,并以内联 `content` 返回。单个读取失败时保留原命中,不附加内容;仅支持 `mode="list"`。 |
| telemetry | bool \| object | 否 | False | 在响应中附带遥测数据 |
`search()` 使用和 `find()` 相同的目标解析和显式标签过滤规则,包括由 `X-OpenViking-Actor-Peer` 或 SDK `actor_peer_id` 选择的 peer 集合过滤。提供 `image_url` 时,`search()` 会直接执行图片检索并跳过会话 query planning。
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index f9415d0cf..2d306aa3f 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -259,6 +259,7 @@ async def find(
min_score: float = 0.35,
level: Optional[List[int]] = None,
context_type: Optional[Union[str, List[str]]] = None,
+ read_content: bool = False,
) -> str:
"""Fast semantic retrieval without session context. Returns ranked memories, resources, and skills with URI, abstract, and score."""
service = get_service()
@@ -274,7 +275,7 @@ async def find(
filter=_resolve_context_type_filter(context_type),
level=level,
)
- return _format_search_result(result)
+ return await _format_search_result(result, service=service, ctx=ctx, read_content=read_content)
@mcp.tool()
@@ -300,6 +301,7 @@ async def search(
other_peer_penalties: Optional[Dict[str, float]] = None,
rewrite: Literal["off", "auto"] = "off",
rewrite_max_bullets: int = 6,
+ read_content: bool = False,
) -> str:
"""Deep semantic retrieval with optional session context and intent analysis.
@@ -313,6 +315,8 @@ async def search(
ctx = _get_ctx()
context_filter = _resolve_context_type_filter(context_type)
if mode == "context":
+ if read_content:
+ raise InvalidArgumentError("read_content is only supported in mode='list'")
if target_uri:
raise InvalidArgumentError("target_uri is not supported in mode='context'")
if detail != "auto" and detail_by_category:
@@ -374,10 +378,10 @@ async def search(
filter=context_filter,
level=level,
)
- return _format_search_result(result)
+ return await _format_search_result(result, service=service, ctx=ctx, read_content=read_content)
-def _format_search_result(result) -> str:
+async def _format_search_result(result, *, service, ctx, read_content: bool = False) -> str:
items = []
for ctx_type, contexts in [
("memory", result.memories),
@@ -390,18 +394,36 @@ def _format_search_result(result) -> str:
if not items:
return "No matching context found."
+ contents: dict[str, str] = {}
+ if read_content:
+ import asyncio
+
+ semaphore = asyncio.Semaphore(10)
+
+ async def _read(uri: str) -> None:
+ async with semaphore:
+ try:
+ contents[uri] = await service.fs.read_visible(uri, ctx=ctx)
+ except Exception:
+ pass
+
+ await asyncio.gather(*(_read(m.uri) for _, m in items))
+
lines = []
for ctx_type, m in items:
abstract = (
getattr(m, "abstract", "") or getattr(m, "overview", "") or "(no abstract)"
).strip()
score = getattr(m, "score", 0.0)
- lines.append(f"- [{ctx_type} {score * 100:.0f}%] {m.uri}\n {abstract}")
+ line = f"- [{ctx_type} {score * 100:.0f}%] {m.uri}\n {abstract}"
+ if m.uri in contents:
+ line += f"\n\n {contents[m.uri]}"
+ lines.append(line)
return (
f"Found {len(items)} item(s):\n\n"
+ "\n".join(lines)
- + "\n\nUse the read tool to expand a URI."
+ + ("" if read_content else "\n\nUse the read tool to expand a URI.")
)
diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.py
index acec157e8..19038008c 100644
--- a/openviking/server/routers/search.py
+++ b/openviking/server/routers/search.py
@@ -2,6 +2,7 @@
# SPDX-License-Identifier: AGPL-3.0
"""Search endpoints for OpenViking HTTP Server."""
+import asyncio
import math
from typing import Any, Dict, List, Literal, Optional, Sequence, Union
@@ -137,6 +138,7 @@ class FindRequest(BaseModel):
until: Optional[str] = None
time_field: Optional[TimeField] = None
level: Optional[Union[int, str, List[int]]] = None
+ read_content: bool = False
telemetry: TelemetryRequest = False
@@ -198,6 +200,7 @@ class SearchRequest(BaseModel):
until: Optional[str] = None
time_field: Optional[TimeField] = None
level: Optional[Union[int, str, List[int]]] = None
+ read_content: bool = False
telemetry: TelemetryRequest = False
mode: Literal["list", "context"] = "list"
@@ -225,12 +228,43 @@ class SearchRequest(BaseModel):
)
return self
+ if self.read_content:
+ raise ValueError("read_content is only supported in mode='list'")
if self.target_uri:
raise ValueError("target_uri is not supported in mode='context'")
_reject_unknown_quota_and_detail(self.quotas, self.detail)
return self
+async def _inline_read_content(
+ result: Any,
+ *,
+ service: Any,
+ ctx: RequestContext,
+) -> Any:
+ """Attach visible file content to ranked hits when it can be read."""
+ if not isinstance(result, dict):
+ return result
+
+ hits = [
+ hit
+ for category in ("memories", "resources", "skills")
+ for hit in result.get(category, [])
+ if isinstance(hit, dict) and isinstance(hit.get("uri"), str)
+ ]
+ semaphore = asyncio.Semaphore(10)
+
+ async def _read(hit: Dict[str, Any]) -> None:
+ async with semaphore:
+ try:
+ hit["content"] = await service.fs.read_visible(hit["uri"], ctx=ctx)
+ except Exception:
+ pass
+
+ await asyncio.gather(*(_read(hit) for hit in hits))
+ return result
+
+
class RecallRequest(BaseModel):
"""Request model for the recall preset over context assembly.
@@ -321,6 +355,8 @@ async def find(
result = execution.result
if hasattr(result, "to_dict"):
result = result.to_dict(include_provenance=request.include_provenance)
+ if request.read_content:
+ result = await _inline_read_content(result, service=service, ctx=_ctx)
result = _sanitize_floats(result)
return Response(
status="ok",
@@ -438,6 +474,8 @@ async def search(
result = execution.result
if hasattr(result, "to_dict"):
result = result.to_dict(include_provenance=request.include_provenance)
+ if request.read_content:
+ result = await _inline_read_content(result, service=service, ctx=_ctx)
result = _sanitize_floats(result)
return Response(
status="ok",
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index 095174018..88cf2919e 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -180,6 +180,31 @@ func TestFindOmitsSearchFiltersWhenUnset(t *testing.T) {
}
}
+func TestFindSendsAndDecodesReadContentWhenEnabled(t *testing.T) {
+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body := readJSONBody(t, r)
+ if body["read_content"] != true {
+ t.Fatalf("read_content = %#v", body["read_content"])
+ }
+ writeOK(t, w, map[string]any{
+ "resources": []map[string]any{{
+ "uri": "viking://resources/auth.md",
+ "content": "full visible content",
+ }},
+ })
+ }))
+ defer closeServer()
+
+ enabled := true
+ result, err := client.Find(context.Background(), "auth", &FindOptions{ReadContent: &enabled})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(result.Resources) != 1 || result.Resources[0].Content != "full visible content" {
+ t.Fatalf("result = %#v", result)
+ }
+}
+
func TestFindUsesDefaultLimitAndPreservesEmptyValues(t *testing.T) {
client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body := readJSONBody(t, r)
diff --git a/sdk/go/retrieval.go b/sdk/go/retrieval.go
index 925368cd0..3f7f10f59 100644
--- a/sdk/go/retrieval.go
+++ b/sdk/go/retrieval.go
@@ -31,6 +31,7 @@ func (c *Client) Find(ctx context.Context, queryText string, opts *FindOptions)
setAny(payload, "filter", opts.Filter)
setAny(payload, "context_type", opts.ContextType)
setAny(payload, "include_provenance", opts.IncludeProvenance)
+ setAny(payload, "read_content", opts.ReadContent)
setString(payload, "since", opts.Since)
setString(payload, "until", opts.Until)
setString(payload, "time_field", opts.TimeField)
@@ -76,6 +77,7 @@ func (c *Client) Search(ctx context.Context, queryText string, opts *SearchOptio
setAny(payload, "filter", opts.Filter)
setAny(payload, "context_type", opts.ContextType)
setAny(payload, "include_provenance", opts.IncludeProvenance)
+ setAny(payload, "read_content", opts.ReadContent)
setString(payload, "since", opts.Since)
setString(payload, "until", opts.Until)
setString(payload, "time_field", opts.TimeField)
diff --git a/sdk/go/types.go b/sdk/go/types.go
index 63947a33a..05dcd00a9 100644
--- a/sdk/go/types.go
+++ b/sdk/go/types.go
@@ -239,6 +239,7 @@ type FindOptions struct {
Filter map[string]any
ContextType any
IncludeProvenance *bool
+ ReadContent *bool
Telemetry any
Since string
Until string
@@ -259,6 +260,7 @@ type SearchOptions struct {
Filter map[string]any
ContextType any
IncludeProvenance *bool
+ ReadContent *bool
Telemetry any
Since string
Until string
@@ -474,6 +476,7 @@ type MatchedContext struct {
ContextType string `json:"context_type,omitempty"`
Level int `json:"level,omitempty"`
Abstract string `json:"abstract,omitempty"`
+ Content string `json:"content,omitempty"`
Overview string `json:"overview,omitempty"`
Category string `json:"category,omitempty"`
Score float64 `json:"score,omitempty"`
diff --git a/sdk/python/openviking_sdk/options.py b/sdk/python/openviking_sdk/options.py
index 76ee9e13e..e04cd5769 100644
--- a/sdk/python/openviking_sdk/options.py
+++ b/sdk/python/openviking_sdk/options.py
@@ -25,6 +25,7 @@ class FindOptions(_ExtraOptions, total=False):
until: str
time_field: TimeField
level: Level
+ read_content: bool
telemetry: Any
diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.py
index 17c27224c..77310b1d3 100644
--- a/sdk/python/tests/test_async_client_behaviors.py
+++ b/sdk/python/tests/test_async_client_behaviors.py
@@ -660,6 +660,25 @@ async def test_find_forwards_level_and_time_filters_when_provided():
assert payload["time_field"] == "updated_at"
+ ("method_name", "kwargs", "expected_path"),
+ [
+ ("find", {}, "/api/v1/search/find"),
+ ("search", {"session_id": "session-1"}, "/api/v1/search/search"),
+ ],
+)
+async def test_retrieval_forwards_read_content(method_name, kwargs, expected_path):
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ client._request = AsyncMock(return_value=object())
+ client._handle_response_data = lambda _response: {"result": {}}
+
+ await getattr(client, method_name)("hello", options={"read_content": True}, **kwargs)
+
+ assert client._request.await_args.args == ("POST", expected_path)
+ assert client._request.await_args.kwargs["json"]["read_content"] is True
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("method_name", "extra_kwargs", "expected_path"),
diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts
index ab98f4349..3118115e4 100644
--- a/sdk/typescript/src/client.ts
+++ b/sdk/typescript/src/client.ts
@@ -388,6 +388,7 @@ export class OpenVikingClient {
level: options.level,
tags: options.tags,
include_provenance: options.includeProvenance,
+ read_content: options.readContent,
});
return this.request("POST", `/api/v1/search/${kind}`, {
body: mergeExtra(body, options.extra),
diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.ts
index ffdfddd83..cc22319b7 100644
--- a/sdk/typescript/src/types.ts
+++ b/sdk/typescript/src/types.ts
@@ -147,6 +147,7 @@ export interface FindOptions {
level?: number[];
tags?: string[];
includeProvenance?: boolean;
+ readContent?: boolean;
extra?: JsonObject;
}
/** Session-aware semantic retrieval options. */
diff --git a/sdk/typescript/tests/client.test.ts b/sdk/typescript/tests/client.test.ts
index 8e702d3d9..74b7d2cf2 100644
--- a/sdk/typescript/tests/client.test.ts
+++ b/sdk/typescript/tests/client.test.ts
@@ -274,6 +274,23 @@ describe("OpenVikingClient", () => {
});
});
+ it("forwards readContent for ranked retrieval", async () => {
+ const fetcher = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(ok({ resources: [] }));
+ const client = new OpenVikingClient({
+ baseUrl: "https://example.com",
+ fetch: fetcher,
+ });
+
+ await client.find("hello", { readContent: true });
+
+ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({
+ query: "hello",
+ read_content: true,
+ });
+ });
+
it("sends dry_run for prune_orphans reindex requests", async () => {
const fetcher = vi
.fn<typeof fetch>()
diff --git a/tests/server/test_api_search.py b/tests/server/test_api_search.py
index 677a23889..cdde5c1b4 100644
--- a/tests/server/test_api_search.py
+++ b/tests/server/test_api_search.py
@@ -56,6 +56,110 @@ async def test_find_basic(client_with_resource):
assert "telemetry" not in body
[email protected]("endpoint", ["/api/v1/search/find", "/api/v1/search/search"])
+async def test_search_endpoints_inline_visible_content_when_requested(
+ client: httpx.AsyncClient, service, monkeypatch, endpoint: str
+):
+ async def fake_read_visible(uri, *, ctx):
+ assert ctx is not None
+ return f"visible content for {uri}"
+
+ async def fake_search(**kwargs):
+ del kwargs
+ return FindResult(
+ memories=[],
+ resources=[
+ MatchedContext(
+ uri="viking://resources/visible.md",
+ context_type=ContextType.RESOURCE,
+ )
+ ],
+ skills=[],
+ )
+
+ monkeypatch.setattr(service.fs, "read_visible", fake_read_visible)
+ monkeypatch.setattr(
+ service.search, "find" if endpoint.endswith("/find") else "search", fake_search
+ )
+
+ response = await client.post(endpoint, json={"query": "visible", "read_content": True})
+
+ assert response.status_code == 200
+ assert response.json()["result"]["resources"][0]["content"] == (
+ "visible content for viking://resources/visible.md"
+ )
+
+
+async def test_find_omits_content_when_read_is_not_requested(
+ client: httpx.AsyncClient, service, monkeypatch
+):
+ async def fake_search(**kwargs):
+ del kwargs
+ return FindResult(
+ memories=[],
+ resources=[
+ MatchedContext(
+ uri="viking://resources/visible.md",
+ context_type=ContextType.RESOURCE,
+ )
+ ],
+ skills=[],
+ )
+
+ monkeypatch.setattr(service.search, "find", fake_search)
+ monkeypatch.setattr(
+ service.fs,
+ "read_visible",
+ lambda *args, **kwargs: pytest.fail("read_visible must not be called"),
+ )
+
+ response = await client.post("/api/v1/search/find", json={"query": "visible"})
+
+ assert response.status_code == 200
+ assert "content" not in response.json()["result"]["resources"][0]
+
+
+async def test_find_keeps_hit_without_content_when_read_fails(
+ client: httpx.AsyncClient, service, monkeypatch
+):
+ async def fake_read_visible(uri, *, ctx):
+ del uri, ctx
+ raise RuntimeError("unavailable")
+
+ async def fake_find(**kwargs):
+ del kwargs
+ return FindResult(
+ memories=[],
+ resources=[
+ MatchedContext(
+ uri="viking://resources/unavailable.md",
+ context_type=ContextType.RESOURCE,
+ )
+ ],
+ skills=[],
+ )
+
+ monkeypatch.setattr(service.fs, "read_visible", fake_read_visible)
+ monkeypatch.setattr(service.search, "find", fake_find)
+
+ response = await client.post(
+ "/api/v1/search/find", json={"query": "unavailable", "read_content": True}
+ )
+
+ assert response.status_code == 200
+ assert "content" not in response.json()["result"]["resources"][0]
+
+
+async def test_search_context_rejects_read_content(client: httpx.AsyncClient):
+ response = await client.post(
+ "/api/v1/search/search",
+ json={"query": "visible", "mode": "context", "read_content": True},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "INVALID_ARGUMENT"
+
+
@pytest.mark.parametrize(
("endpoint", "service_method"),
[
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index 22eda273e..5b03c2545 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -304,6 +304,41 @@ async def test_find_tool_calls_lightweight_find(service, monkeypatch):
}
+async def test_find_tool_inlines_visible_content_when_requested(service, monkeypatch):
+ async def fake_find(**kwargs):
+ del kwargs
+ return SimpleNamespace(
+ memories=[],
+ resources=[
+ SimpleNamespace(
+ uri="viking://resources/visible.md",
+ abstract="summary",
+ overview="",
+ score=0.9,
+ )
+ ],
+ skills=[],
+ )
+
+ async def fake_read_visible(uri, *, ctx):
+ assert uri == "viking://resources/visible.md"
+ assert ctx == DEFAULT_CTX
+ return "full visible content"
+
+ monkeypatch.setattr(service.search, "find", fake_find)
+ monkeypatch.setattr(service.fs, "read_visible", fake_read_visible)
+
+ result = await mcp_endpoint.find(query="visible", read_content=True)
+
+ assert "full visible content" in result
+ assert "Use the read tool" not in result
+
+
+async def test_search_tool_rejects_read_content_in_context_mode():
+ with pytest.raises(InvalidArgumentError, match="read_content"):
+ await mcp_endpoint.search(query="visible", mode="context", read_content=True)
+
+
async def test_search_tool_calls_context_aware_search_with_session(service, monkeypatch):
captured = {}
session = SimpleNamespace(load_called=False)