On this page

Follow a search request through Core

Start at the HTTP boundary

POST /api/v1/spaces/{space_id}/search takes a query and returns ranked passages. Route declaration

  1. Caddy

    Sends /api/* to Django.

  2. DocumentSearch.post

    Passes the principal, space UUID and typed body.

  3. RetrieveDocuments

    Checks access, filters and corpus readiness.

  4. QueryEngine

    Retrieves and ranks passages.

    @modify(
        status_code=HTTPStatus.OK,
        operation_id='searchSpace',
        extra_responses=raises(
            exceptions.CorpusNotInitializedError,
            exceptions.CorpusRecoveringError,
            exceptions.CorpusChangedError,
            exceptions.SpaceNotFoundError,
            exceptions.InvalidMetadataFilterError,
            exceptions.QueryFilterUnsupportedError,
            exceptions.RetrievalSettingsUnsupportedError,
            exceptions.LLMNotConfiguredError,
            exceptions.SpaceStorageUnreachableError,
            exceptions.StoredPointUnreadableError,
            exceptions.LateChunkingPoolingError,
        ),
    )
    @inject
    @mcp_tool(
        name='search_knowledge_base',
        description=(
            'Search a knowledge base and get back the passages that match, '
            'ranked, with no answer written for you. Prefer this over '
            'answer_from_knowledge_base: you can read the passages and '
            'reason over them yourself, which is cheaper and keeps your own '
            'context. Passage texts come back shortened; call fetch_source '
            'with a passage id to read one in full.'
        ),
        input_fields=('query', 'top_k'),
        max_top_k=RETRIEVAL_TOP_K_CEILING,
        cost=ToolCost.cheap,
    )
    async def post(
        self,
        parsed_path: Path[DocumentPath],
        parsed_body: BodyMsgspec[RetrievalRequestPayload],
        retrieve_documents: FromDishka[RetrieveDocuments],
    ) -> RetrieveResultPayload:
        """Retrieve and rank the most relevant chunks, without generating.

        Only a member of the space may search it: a non-member is told the space
        was not found. Searching only needs read access, which every membership
        role grants, so a member is never forbidden -- no 403 arises here.
        Plain retrieval needs no LLM, but a read path that names an LLM step
        (HyDE, the LLM-judge reranker) does; a space that named one with no LLM
        configured is answered with a 409.

        A request that narrows the search settles its filter first: a filter
        breaking the bounds, or naming something the space was never declared
        to be selectable by, is a 400, and one its retrieval legs could not
        honour is a 409 rather than a search quietly made around it.
        """
        principal = principal_from_request(self.request)
        return await retrieve_documents(
            principal,
            parsed_path.space_id,
            parsed_body,
        )

Read the use case and its contracts

The controller decodes the request as RetrievalRequestPayload. The Dishka provider supplies request-specific collaborators in SESSION scope.

RetrieveDocuments checks SpaceAction.view, metadata filter support and corpus admission before calling QueryEngine.retrieve_sources under the space’s outbound route. A configured stage may call a model, for example to rewrite the query.

Search returns ranked sources and retrieval evidence in RetrieveResultPayload. Answer generation starts at QueryDocuments.

  • Controllers. Parse and declare HTTP payloads. Use public UUIDs in routes and DTOs.

  • logic. Keep authorization and use-case decisions here. Define a port for replaceable infrastructure and wire its implementation via DI.

  • infra and models. Read through selectors, write through mutations and convert payloads with mappers. Keep ORM queries in infra and schemas in models. Add a focused test for changes to selected rows or writes.

  • DI scopes. Use application scope for shared services and request or session scope for dependencies tied to a request. Middleware opens a child scope per request. Container builder

Follow a write for comparison

The upload controller validates multipart input and calls IngestDocument. The use case checks access, metadata and storage permissions, then ingests a managed revision or appends to attached storage. Replace the extractor port implementation independently of transport. Upload, original replacement and reindexing have separate contracts. Processing and indexing

Test the real route with its DI wiring and access rules. Read back published data using an authorized account. Check failures at the same boundary, such as missing access, an invalid filter or an unavailable provider.

ContextBase0.1.0

Search the documentation