Module: Parse::Retrieval::AgentTool
- Defined in:
- lib/parse/retrieval/agent_tool.rb
Overview
The semantic_search agent tool: the agent-aware wrapper around
retrieve. It applies the agent security
envelope that retrieve (a model-layer method) is
deliberately kept free of:
- Class allowlist via Agent::MetadataRegistry.resolve_searchable!
(
agent_searchableopt-in, hidden-class refusal, tenant-scope gate). - Recursive underscore-key refusal + filter-field allowlist on
caller-supplied
filter:/vector_filter:. - Tenant scope merged into the Atlas pre-filter AND re-asserted on every returned source record (NEW-TOOLS-3 guard).
field_allowlistprojection of each source record on the way out.- Score quantization in non-admin contexts.
ACL is enforced mongo-direct inside find_similar via the agent's
acl_scope_kwargs (session_token: / acl_user: / acl_role: /
master:), which is why the tool is client_safe: true: a
session-token client routes through the one path with first-class
SDK-side _rperm enforcement.
Constant Summary collapse
- MAX_K =
Upper bound on
k(mirrors the registered parameter schema). 20- DEFAULT_K =
Default neighbour count for the agent tool. Intentionally lower than Parse::Retrieval.retrieve's library default of 10: an LLM tool result is paid for in context tokens, so the agent surface defaults conservatively. Callers/LLMs can raise it up to MAX_K per call.
5- DEFAULT_MAX_TOTAL_TOKENS =
Default ceiling on total returned chunk-content tokens (estimated as chars/4). The retrieve count caps (k * max_chunks_per_document) bound the NUMBER of chunks but not their total size, so a few long documents could silently blow the context window. This budget trims the (score-ordered) chunk list and reports
budget_truncatedso the truncation is never silent. Passmax_total_tokens: 0to disable. 20_000- MAX_QUERY_CHARS =
Longest
queryaccepted. A search query is a short natural-language request; the bound keeps one call from sending a body-sized string to the embedding provider and, under a reranking profile, pairing it with every candidate document. 4_000- PER_AGENT_BUILTIN_COLUMNS =
Built-in columns a per-agent filter may name, with their stored names.
{ "objectId" => "_id", "createdAt" => "_created_at", "updatedAt" => "_updated_at", }.freeze
- ENVELOPE_OVERHEAD_CHARS =
Characters the response envelope adds once (counts, profile, truncation flags, the
documentsmap wrapper). 400- PARAMETERS =
JSON Schema for the registered tool's parameters.
{ "type" => "object", "properties" => { "class_name" => { "type" => "string", "description" => "Parse class name (must be agent_searchable)." }, "query" => { "type" => "string", "description" => "Natural-language query.", "maxLength" => MAX_QUERY_CHARS }, "k" => { "type" => "integer", "default" => DEFAULT_K, "minimum" => 1, "maximum" => MAX_K }, "filter" => { "type" => "object", "description" => "Post-search field filter (allowlisted fields only)." }, "vector_filter" => { "type" => "object", "description" => "Atlas pre-search filter (allowlisted fields only)." }, "text_field" => { "type" => "string", "description" => "Which embedded text source to chunk and return as content. Required only when the class embeds more than one text field; must name one of those sources." }, "profile" => { "type" => "string", "description" => "Optional server-configured retrieval profile name (for example fast, balanced, precise). Profiles set result counts, hybrid search, and reranking; omit for the default search. An unknown name is refused with the list of available profiles." }, "chunk_size" => { "type" => "integer", "description" => "Override chunk window size." }, "chunk_overlap" => { "type" => "integer", "description" => "Override chunk overlap." }, "chunk_by" => { "type" => "string", "enum" => %w[chars tokens], "description" => "Chunk unit." }, "max_chunks_per_document" => { "type" => "integer", "minimum" => 1, "description" => "Cap on chunks emitted per matched document." }, "max_total_tokens" => { "type" => "integer", "minimum" => 0, "description" => "Ceiling on total returned chunk-content tokens (approx chars/4). Trims lowest-ranked chunks first and sets budget_truncated. 0 disables." }, }, "required" => %w[class_name query], }.freeze
- OUTPUT_SCHEMA =
MCP outputSchema → mirrored as structuredContent on results. The parent record of each chunk is hoisted into
documents(keyed by objectId) rather than duplicated inline on every chunk; map a chunk to its source viametadata.object_id. { "type" => "object", "properties" => { "chunks" => { "type" => "array", "items" => { "type" => "object", "properties" => { "id" => { "type" => "string" }, "score" => { "type" => %w[number null] }, "content" => { "type" => "string" }, "metadata" => { "type" => "object" }, }, }, }, "documents" => { "type" => "object", "description" => "objectId => projected source record (sent once per matched document).", }, "count" => { "type" => "integer" }, "budget_truncated" => { "type" => "boolean", "description" => "Present when the token budget dropped lowest-ranked chunks." }, "budget_dropped" => { "type" => "integer", "description" => "Number of chunks dropped by the token budget." }, }, }.freeze
Class Method Summary collapse
- .apply_token_budget(chunks, budget, strict: false) ⇒ Object
-
.register! ⇒ Object
Register the tool.
-
.retrieval_auth_kwargs(agent) ⇒ Object
The agent's auth kwargs for the direct path, including its client when the agent can supply one.
-
.semantic_search(agent, **args) ⇒ Hash
{ chunks: Array<Hash>, documents: Hash, count: Integer }— each chunk's parent record is hoisted once intodocuments(keyed by objectId) instead of being duplicated on every chunk.
Class Method Details
.apply_token_budget(chunks, budget, strict: false) ⇒ Object
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 |
# File 'lib/parse/retrieval/agent_tool.rb', line 520 def apply_token_budget(chunks, budget, strict: false) return [chunks, 0] if budget.nil? || chunks.empty? # Every chunk carries metadata and per-chunk keys alongside its text, # so a response of many tiny chunks is mostly overhead; count it. total = (ENVELOPE_OVERHEAD_CHARS / 4.0).ceil kept = [] seen_docs = {} chunks.each do |chunk| = chunk.respond_to?(:metadata) ? chunk. : nil = .is_a?(Hash) ? (JSON.generate().length rescue 0) : 0 est = ((chunk.content.to_s.length + + CHUNK_OVERHEAD_CHARS) / 4.0).ceil oid = chunk.respond_to?(:metadata) && chunk..is_a?(Hash) ? chunk.[:object_id] : nil if oid && !seen_docs.key?(oid) && chunk.respond_to?(:source) && chunk.source doc_est = (JSON.generate(chunk.source).length / 4.0).ceil rescue 0 est += doc_est end break unless (kept.empty? && !strict) || total + est <= budget kept << chunk seen_docs[oid] = true if oid total += est end [kept, chunks.length - kept.length] end |
.register! ⇒ Object
Register the tool. Idempotent-ish: re-requiring is a no-op because require caches; an explicit re-register after reset_registry! is supported via register!.
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 |
# File 'lib/parse/retrieval/agent_tool.rb', line 771 def register! Parse::Agent::Tools.register( name: :semantic_search, description: "Find documents semantically similar to a natural-language query and " \ "return scored text chunks. Use when keyword matching is unlikely to " \ "work or the question needs synthesizing across documents. The target " \ "class must be declared `agent_searchable`.", parameters: PARAMETERS, permission: :readonly, timeout: 30, output_schema: OUTPUT_SCHEMA, client_safe: true, handler: ->(agent, **args) { Parse::Retrieval::AgentTool.semantic_search(agent, **args) }, ) end |
.retrieval_auth_kwargs(agent) ⇒ Object
The agent's auth kwargs for the direct path, including its client when the agent can supply one.
Agents are duck-typed at this boundary, so an agent-shaped object
that predates direct_auth_kwargs still works and simply resolves as
an unidentified caller, which Parse::MongoDB's binding guard already
models. Requiring the new method of every stand-in would break each
one that has not been updated, to gain a field that is optional by
construction.
39 40 41 42 |
# File 'lib/parse/retrieval/agent_tool.rb', line 39 def retrieval_auth_kwargs(agent) return agent.direct_auth_kwargs if agent.respond_to?(:direct_auth_kwargs) agent.acl_scope_kwargs end |
.semantic_search(agent, **args) ⇒ Hash
Returns { chunks: Array<Hash>, documents: Hash, count: Integer }
— each chunk's parent record is hoisted once into documents (keyed
by objectId) instead of being duplicated on every chunk. When the
token budget trims the result, budget_truncated: true and
budget_dropped: <n> are added.
84 85 86 87 88 89 90 91 92 |
# File 'lib/parse/retrieval/agent_tool.rb', line 84 def semantic_search(agent, **args) started = monotonic_now semantic_search_unobserved(agent, **args) rescue StandardError => e # Failures are observable too: one sanitized event naming the error # class (never its message, which can echo input). emit_failure_event(args, e, started) raise end |