Skip to content

MCP layer

The FastMCP server exposing the six agent-facing tools over stdio and streamable HTTP.

noesis.mcp.server

FastMCP tool server — all six M6 tools as thin wrappers over core/.

Every tool body is the same core call its REST twin makes (routes.py), and the success payloads are identical dicts — tests assert byte-equality so the two surfaces cannot drift (§ M6). Failures raise ToolError carrying the same detail REST puts in the HTTP error body.

The server is transport-agnostic: noesis.app mounts http_app() at /mcp (streamable HTTP), python -m noesis.mcp runs stdio. Tools reach the shared core resources through get_ctx — a callable, not an import, so this module never imports noesis.app (no cycle) and stdio can supply a context of its own.

build_mcp(get_ctx, *, lifespan=None)

Create the noesis MCP server. get_ctx() must return the live AppContext (conn, store, embedder, reranker, structural settings) — called per tool invocation so the context can be built after the server (lifespan order is the transport's concern). lifespan is the stdio entry point's hook for building that context (the HTTP mount builds it in the FastAPI lifespan instead).

Source code in src/noesis/mcp/server.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def build_mcp(get_ctx: Callable[[], Any], *, lifespan: Any | None = None) -> FastMCP:
    """Create the noesis MCP server. ``get_ctx()`` must return the live
    AppContext (conn, store, embedder, reranker, structural settings) —
    called per tool invocation so the context can be built after the
    server (lifespan order is the transport's concern). ``lifespan`` is
    the stdio entry point's hook for building that context (the HTTP
    mount builds it in the FastAPI lifespan instead)."""
    mcp = FastMCP("noesis", lifespan=lifespan)

    @mcp.tool
    async def search_code(
        query: str = Field(min_length=1),
        project_id: str = Field(),
        top_k: int = Field(default=10, ge=1, le=100),
        language: str | None = None,
        channel: Literal["hybrid", "dense", "sparse"] = "hybrid",
        rerank: bool | None = None,
    ) -> dict[str, Any]:
        """Semantic + lexical (hybrid) search over an indexed project.

        Returns ranked spans: {chunk_id, file_path, start_line, end_line,
        language, symbol_name, score, snippet}. Results are candidates,
        not ground truth — read the live file before acting on a span.
        Use get_chunk(chunk_id) to fetch a hit's full stored text.
        """
        # min_length rejects "" in validation; whitespace-only survives it and
        # is the same wasted work (empty BM25 document, dense embed of
        # nothing), so it is refused here — the REST twin does the same in a
        # field_validator.
        if not query.strip():
            raise ToolError("query must not be blank")
        ctx = get_ctx()
        if state.get_project(ctx.conn, project_id) is None:
            raise ToolError("unknown project_id")
        t0 = time.perf_counter()
        try:
            result = await retriever.search_code(
                ctx.store,
                ctx.embedder,
                query,
                project_id,
                top_k=top_k,
                language=language,
                channel=channel,
                reranker=ctx.reranker,
                rerank=rerank,
                candidates=ctx.rerank_candidates,
                gate=ctx.search_gate,
            )
        except SearchOverloaded as exc:
            # MCP has no status codes, so the agent-facing equivalent of a
            # 429 is a ToolError whose text says what happened, that nothing
            # failed, what to do now, and which knob changes it (ADR-84).
            raise ToolError(exc.agent_message()) from exc
        await ctx.telemetry.record_query(
            ctx.conn,
            interface="mcp",
            kind="search",
            project_id=project_id,
            channel=channel,
            reranked=result["reranked"],
            latency_ms=(time.perf_counter() - t0) * 1000,
            result_count=len(result["hits"]),
        )
        return {
            "query": query,
            "channel": channel,
            "reranked": result["reranked"],
            "hits": result["hits"],
        }

    @mcp.tool
    async def structural_search(
        pattern: str,
        language: str,
        project_id: str,
        paths: list[str] | None = None,
        max_results: int | None = Field(default=None, ge=1),
    ) -> dict[str, Any]:
        """AST-pattern search (ast-grep) over the project's live files.

        `pattern` is an ast-grep pattern, e.g. "def $NAME($$$ARGS): $$$BODY"
        (Python) or "console.log($$$A)" (TypeScript). Matches are exact
        syntax-tree matches, not text. `paths` restricts to relative
        path prefixes. Scans the live filesystem — results are current
        even if the index is stale.
        """
        ctx = get_ctx()
        t0 = time.perf_counter()
        try:
            result = await structural_mod.structural_search(
                ctx.conn,
                project_id,
                pattern,
                language,
                paths=paths,
                max_results=max_results,
                settings=ctx.structural,
            )
        except structural_mod.StructuralSearchError as exc:
            raise ToolError(f"{exc.error_type}: {exc.message}") from exc
        await ctx.telemetry.record_query(
            ctx.conn,
            interface="mcp",
            kind="structural",
            project_id=project_id,
            latency_ms=(time.perf_counter() - t0) * 1000,
            result_count=len(result.get("matches", [])),
        )
        return {"pattern": pattern, "language": language, **result}

    @mcp.tool
    async def list_projects() -> list[dict[str, Any]]:
        """List registered projects with root path, embedding model and
        timestamps. Project ids from here feed every other tool."""
        ctx = get_ctx()
        return [dict(row) for row in state.list_projects(ctx.conn)]

    @mcp.tool
    async def get_index_status(project_id: str) -> dict[str, Any]:
        """Status of the most recent index run for a project: status
        (never_indexed | running | done | failed), file/chunk counts,
        timestamps, error. Poll after reindex until status is done."""
        ctx = get_ctx()
        if state.get_project(ctx.conn, project_id) is None:
            raise ToolError("unknown project_id")
        # index_status keeps its quick state reads on the loop (shared conn
        # is loop-owned) and internally offloads only the Qdrant count
        # round-trip (same reason as get_chunk below).
        return await jobs.index_status(ctx, project_id)

    @mcp.tool
    async def get_chunk(chunk_id: str) -> dict[str, Any]:
        """Fetch one indexed chunk by id (ids come from search_code hits).

        Returns the exact stored span with full chunk content — the
        indexed snapshot, which may lag the live file.
        """
        ctx = get_ctx()
        # Off the event loop: this is a synchronous Qdrant network round
        # trip (same reason retriever.search_code wraps store.search) — a
        # slow store must not stall every other in-flight request.
        chunk = await asyncio.to_thread(ctx.store.get_chunk, chunk_id)
        if chunk is None:
            raise ToolError("unknown chunk_id")
        return chunk

    @mcp.tool
    async def reindex(project_id: str) -> dict[str, str]:
        """Re-index a registered project (incremental — only changed files
        are re-embedded). Returns immediately with a run_id; poll
        get_index_status for completion.

        If a project's scan finds zero files while the index still tracks
        some, the run fails rather than emptying the project — report that to
        the human running this service; it cannot be resolved from here."""
        ctx = get_ctx()
        project = state.get_project(ctx.conn, project_id)
        if project is None:
            raise ToolError("unknown project_id")
        try:
            # No `force` here, deliberately: ADR-55 makes the empty-root
            # assertion an OPERATOR call, and the caller of an MCP tool is an
            # agent. Leaving it off keeps a whole-project purge out of the
            # model's action space and out of any tool description that would
            # read as a procedure for reaching it.
            #
            # Stated precisely, because the earlier wording overclaimed (PR #24
            # round-8 review): this is an affordance, NOT an access boundary.
            # `verify_local_origin` passes when Origin/Referer are absent, so
            # any local process — including an agent holding a shell — can send
            # `?force=true` itself. What the omission buys is that nothing here
            # suggests it should. The REST surface keeps
            # it (`?force=true` on POST /projects/{id}/reindex), which is a
            # human with curl or anything else that speaks the JSON API. NOT
            # the dashboard: its Reindex button posts to that same route
            # (`api/static/app.js`) but never sends the parameter, so a
            # dashboard-only operator cannot reach the escape (PR #24 round-7
            # review). `docs/reference/dashboard.md` points them at the curl.
            return jobs.launch_index_run(ctx, project["root_path"])
        except state.IndexCapacityReached as exc:
            # Agent-readable equivalent of a 429 (ADR-85): says nothing was
            # started, so the agent retries rather than assuming it is queued.
            raise ToolError(exc.agent_message()) from exc
        except ValueError as exc:  # mixed-model guard
            raise ToolError(str(exc)) from exc

    return mcp