Serve the semantic layer over MCP

읽는 데 약 56분분 걸린다, 7절에 5개 예제이(가) 있음.

2026.11.15판 예제 통과 2026년 11월 19 78개 예제 중 78개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.15판을 번역한 것이다. 원문 읽기

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

By the end of this chapter, you can serve the shop's governed metrics as MCP tools that answer for the role the server was built for, return each answer with its provenance as structured data, test the server in memory, and run the book's agent through it as a host.

The shop's teams ask their questions from the assistant each person already uses, but the agent so far lives inside the book's Python: chapter 6 gave it five metric tools over the semantic layer, and chapter 9 put each role's row filters, column masks and minimum group size underneath them, in lib/policies.py. People in the shop don't work inside that Python. Each assistant, a chat app on a desktop or an editor with an agent built in, could get its own copy of the tools, and then each copy would need its own copy of the access rules, kept in step by hand. The first copy that drifts gives a regional lead another region's revenue.

The Model Context Protocol (MCP) removes the copies. MCP is an open protocol in which an application, the host, runs a client for each server it connects to, and a server offers tools that the host's model can call. Model Context Protocol in Practice covers the protocol, from host, client and server to authorization. Here, the shop's semantic layer becomes one MCP server, which this chapter calls the semantic server, in lib/semantic_server.py. It offers the same five tools as the in-process agent, through chapter 9's PolicyToolbox, the metric tools with the role's access rules underneath, so every host that connects gets the same metrics and the same rules. The examples use the Python software development kit for MCP, mcp 2.3.0, which speaks the specification's revision 2026-07-28, and every one of them runs in memory, with no port and no process.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Turn metrics into tools

마지막으로 변경된 판: 2026.11.12판

An MCP tool is a name, a description the model reads, a JSON Schema for its arguments and, optionally, a schema for its result. A client discovers a server's tools with tools/list and calls one with tools/call. The specification says the list must not vary per connection, though it may vary with the authorization presented on the request, and that servers should return tools in a deterministic order (tools). So the questions for a semantic layer are which tools to offer, and whether a role should see fewer of them.

We recommend offering the tools the agent already has. Chapter 6 chose five for the shop's agent: list_metrics, describe_metric, query_metric, ask_back and cannot_answer. They were measured on the golden questions, whose answers were checked by running them, and they ask the model to choose a metric request, never to write SQL. build_server() in lib/semantic_server.py registers one MCP tool for each, with a description the model reads and typed arguments, and each tool body calls the same method of chapter 9's PolicyToolbox that the in-process agent calls. The tools are registered in name order. Each is marked read-only, idempotent and closed-world with MCP's tool annotations. Model Context Protocol in Practice explains how to write descriptions the model reads and why annotations are hints, not guarantees.

What a role changes is easiest to see side by side: a server for the analyst, who sees everything, and one for the support team, who may see no revenue. The code lists each server's tools and compares its list_metrics catalog with the one the in-process agent puts in its prompt.

list-metric-tools.py Python 3.12.15 · anyio 4.16.0 · duckdb 2.0.0 · mcp 2.3.0 · pydantic 2.14.3 · pyyaml 6.0.3 · sqlglot 30.31.0 통과
"""The semantic layer as an MCP server: the tools it lists, what query_metric takes, and each role's catalog.The `support, metrics` line settles that support's catalog holds no revenue metric, and the `same catalog as thein-process agent` lines settle that each catalog is the prompt's own text."""import anyiofrom mcp import Clientfrom lib.metric_tools import catalogfrom lib.policies import PolicyLayer, policy_forfrom lib.semantic import loadfrom lib.semantic_server import build_serverfrom lib.warehouse import connectcon, layer = connect(), load()async def main():    listed = {}    for role in ("analyst", "support"):        async with Client(build_server(role, shop=con, layer=layer)) as client:   # in memory: no port, no process            tools = (await client.list_tools()).tools            text = (await client.call_tool("list_metrics", {})).structured_content["text"]        listed[role] = [t.name for t in tools]        metrics = [line[2:].split(":")[0] for line in text.splitlines()]   # catalog lines start with "- ", then the name        print(f"{role}, tools: {', '.join(listed[role])}")        print(f"{role}, metrics in list_metrics: {len(metrics)}")        print(f"{role}, metrics: {', '.join(metrics)}")        in_process = catalog(PolicyLayer(layer, policy_for(role), con))        same = text == in_process                  # PolicyLayer builds the in-process prompt's catalog, so MCP must match it        assert same        print(f"{role}, same catalog as the in-process agent: {'yes' if same else 'no'}")    query = next(t for t in tools if t.name == "query_metric")    print(f"query_metric inputs: {', '.join(query.input_schema['properties'])}")    print(f"query_metric requires: {', '.join(query.input_schema['required'])}")    print(f"tools marked read-only: {sum(t.annotations.read_only_hint for t in tools)} of {len(tools)}")    print(f"tools with a role input: {sum('role' in t.input_schema['properties'] for t in tools)}")    print(f"same tool list for both roles: {listed['analyst'] == listed['support']}")anyio.run(main)
출력python list-metric-tools.py
analyst, tools: ask_back, cannot_answer, describe_metric, list_metrics, query_metric
analyst, metrics in list_metrics: 10
analyst, metrics: net_revenue, gross_revenue, orders, line_net_revenue, units_sold, refunds, order_refunds, new_customers, refund_rate, average_order_value
analyst, same catalog as the in-process agent: yes
support, tools: ask_back, cannot_answer, describe_metric, list_metrics, query_metric
support, metrics in list_metrics: 5
support, metrics: orders, units_sold, refunds, order_refunds, new_customers
support, same catalog as the in-process agent: yes
query_metric inputs: metrics, group_by, filters, order_by, limit
query_metric requires: metrics
tools marked read-only: 5 of 5
tools with a role input: 0
same tool list for both roles: True

Both servers list the same tools: ask_back, cannot_answer, describe_metric, list_metrics, query_metric. What differs is the catalog. The analyst's list_metrics returns 10 metrics and support's 5: orders, units_sold, refunds, order_refunds, new_customers. Every revenue metric is gone from support's catalog, because chapter 9's PolicyLayer hides any metric that reads a column its role is denied. For both roles, the catalog over MCP is the same text the in-process agent puts in its prompt. That matters for the host: an unchanged catalog means an unchanged prompt.

query_metric takes metrics, group_by, filters, order_by, limit and requires only metrics. Of the server's tools, 5 of 5 are marked read-only, and 0 take an argument called role, which is the subject of the next section.

Keeping one tool list for every role was a choice. The specification would allow support's server to list fewer tools, but each of the five tools is useful to every role, and the role changes what a tool returns, not whether it exists. A role that can't use a tool at all is the case for shortening the list, and Model Context Protocol in Practice covers scope tools by what the token allows. The cost of a long list is the subject of the same book's keep the tool list small.

Working rule: Serve the tools your agent was measured with, each one a thin call into the same code the in-process agent uses, so that the server can't drift from what you tested. List them in a fixed order and mark them read-only. Let the role change what a tool returns, and shorten the tool list only when a role can't use a tool at all.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Carry the caller's role into every query

마지막으로 변경된 판: 2026.11.15판

A server that enforces chapter 9's access rules has to know whose rules to enforce, and that's the part an MCP server most often gets wrong. Revision 2026-07-28 has no protocol-level sessions: it removed the initialize handshake and the Mcp-Session-Id header, so every request stands alone (changelog). There's no session to hold a role. The specification gives two places for identity instead. A server that a host launches over stdio, for one person, "SHOULD NOT" use MCP's authorization and should take credentials from the environment (authorization). A server on HTTP derives the user from a verified access token: the specification's security guidance, on binding a server's state to a user, derives the user ID from the verified token, not from anything the client supplies (security best practices).

The tempting third place is a tool argument: give query_metric a role parameter and let the host fill it in. Then the role is whatever the caller sends, and the caller is a model that reads questions and, as chapter 9 showed, text inside the data. Three servers answer one request. Each receives gq-017, net revenue in each of "our countries" in 2025, asked by EMEA's regional lead, with "role": "analyst" added to the arguments. The first server takes the role as an argument. The second is the semantic server, built for EMEA's lead with build_server("regional_lead", "EMEA"). The third is built by server_from_environment(), which reads SHOP_ROLE and SHOP_REGION as a host would set them when it launches the server for one person. Last, the request runs once more on that third server's database, through the plain semantic layer with no policy, as the paragraph after the results explains.

role-bound-at-build.py Python 3.12.15 · anyio 4.16.0 · duckdb 2.0.0 · mcp 2.3.0 · pydantic 2.14.3 · pyyaml 6.0.3 · sqlglot 30.31.0 통과
"""gq-017 from EMEA's regional lead, sent with role "analyst": a server that takes the role as an argument obeys it,and one that binds the role when it is built ignores it, and queries a database that holds only the lead's rows.The `role as argument, countries` line shows every country a request-supplied role returns, and the `role bound atbuild, countries` line settles that a server built for the lead returns EMEA's countries only."""import anyiofrom mcp import Clientfrom mcp.server.mcpserver import MCPServerfrom lib.policies import PolicyLayer, PolicyToolbox, policy_forfrom lib.semantic import MetricRequest, loadfrom lib.semantic_server import build_server, server_from_environmentfrom lib.warehouse import connectcon, layer = connect(), load()naive = MCPServer("role-as-argument")@naive.tool()def query_metric(metrics: list[str], group_by: list[str] = [], filters: dict = {}, role: str = "analyst",                 region: str | None = None) -> list[list]:    """The anti-pattern: whoever calls the tool says who they are, and it queries the whole warehouse."""    toolbox = PolicyToolbox(con, PolicyLayer(layer, policy_for(role, region), con))    return [list(row) for row in toolbox.query_metric({"metrics": metrics, "group_by": group_by,                                                       "filters": filters}).answer.rows]request = {"metrics": ["net_revenue"], "group_by": ["order__country"], "filters": {"metric_time__year": 2025},           "role": "analyst"}                     # the lead's request, with a role the lead doesn't haveenvironment = {"SHOP_ROLE": "regional_lead", "SHOP_REGION": "EMEA"}   # what a host sets for a stdio serverasync def main():    servers = {"role as argument": naive, "role bound at build": build_server("regional_lead", "EMEA", con, layer),               "role from the environment": (stdio := server_from_environment(environment, con))}    for name, server in servers.items():        async with Client(server) as client:            result = (await client.call_tool("query_metric", request)).structured_content        rows = result["result"] if "result" in result else result["answer"]["rows"]        print(f"{name}, countries: {', '.join(row[0] for row in rows)}")        if "answer" in result:            provenance = result["answer"]["provenance"]            print(f"{name}, provenance: role {provenance['role']}, row filter {provenance['filters']['row filter']}")    # The policy bypassed: the plain semantic layer, which applies no role, on the stdio server's own database.    bypass = layer.query(stdio.database, MetricRequest.from_arguments({k: v for k, v in request.items() if k != "role"}))    print(f"role from the environment, no policy, countries: {', '.join(row[0] for row in bypass.rows)}")anyio.run(main)
출력python role-bound-at-build.py
role as argument, countries: AU, CA, DE, ES, FR, GB, JP, NL, SG, US
role bound at build, countries: DE, ES, FR, GB, NL
role bound at build, provenance: role regional_lead, row filter EMEA only
role from the environment, countries: DE, ES, FR, GB, NL
role from the environment, provenance: role regional_lead, row filter EMEA only
role from the environment, no policy, countries: DE, ES, FR, GB, NL

The server that takes the role as an argument returned AU, CA, DE, ES, FR, GB, JP, NL, SG, US: every country in the shop, because the request said "analyst" and the server believed it. The semantic server returned DE, ES, FR, GB, NL, EMEA's countries only, and its provenance says why: role regional_lead, row filter EMEA only. Its tools have no role parameter, so the extra argument went nowhere: the SDK validated the arguments against each tool's parameters, dropped the one it didn't know, and ran the call. The server built from the environment returned DE, ES, FR, GB, NL. Binding the role at build means one server per person, which is what stdio gives you: the host starts a process for its user, and the process lives as long as the host needs it (Choose stdio or Streamable HTTP).

The binding decides two things, and the database is the first. The book's primary access control is what the database allows each role: a read-only connection to that role's own views, which hold only its rows and columns, as chapter 7 built it, with chapter 9's policy rewrite as a second layer behind it. So build_server() doesn't take a connection to query. It takes the shop's warehouse, derives the role's policy, and opens the role's own database with agent_warehouse(shop, policy=policy, semantic=SEMANTIC_TABLES): chapter 7's database, plus the semantic layer's views and calendar as the role sees them, so that metrics can run on it. Every tool queries that database, and no caller can pair a role with another role's. The final step runs the lead's request through the plain semantic layer, which applies no role, on the environment server's own database. It returned DE, ES, FR, GB, NL: with the policy bypassed, there are still only EMEA's rows to read.

The second is what counts as forbidden, which the policy alone decides: a filter on region with any value but the lead's own is forbidden. Any other value the lead's rows don't hold, such as another region's country, gets a correctable error listing the lead's own values, whether it exists elsewhere or not, so it reveals nothing (chapter 9).

A server on HTTP serves many people, so it can't bind a role when it starts. It needs the role on each request, from the token. In the Python SDK, the server is given a TokenVerifier whose verify_token() returns an AccessToken with the client's ID, its scopes and the token's claims, and a tool reads the verified token with get_access_token() (mcp/server/auth/provider.py, mcp/server/auth/middleware/auth_context.py). The server would map a claim to a role and region there, and choose that role's database and policy for the call. The token must have been issued for this server: servers must check that each access token was issued for them, as its intended audience (authorization), which Model Context Protocol in Practice builds in bind each token to one server. Scopes don't replace the access rules. A scope can say that a token may call query_metric; only the database and the policy can say which rows it reads, and the specification's security guidance lists trusting the scopes a token claims, with no server-side check, as a common mistake (security best practices). Nothing here runs this path, because an in-memory client has no HTTP layer, so no bearer token reaches the server, and get_access_token() returns None there.

Working rule: Bind the role where the person was authenticated, never in a tool's arguments. For a stdio server, the host passes the role in the environment, and the server opens that role's read-only database and builds its policy once. For an HTTP server, take the role from a verified token issued for this server, on every request, and enforce the role's rows in the database and the policy whatever the token's scopes say. Leave role out of every input schema, so there's nothing for a model or a question to fill in, and log any argument a tool ignores, role first, because one is a sign that text the model read is steering it (treat ticket text as untrusted data).

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Return answers with their provenance

마지막으로 변경된 판: 2026.11.15판

With the role bound, the server's answers are right for the person asking. The host still has to know what each answer is: which metric produced it, with which filters, for which role and from data how fresh. Chapter 1 called that an answer's provenance, and the in-process agent keeps it in Answer.provenance. Over MCP, a tool can declare an outputSchema and return structuredContent that conforms to it, and a tool that does "SHOULD also return the serialized JSON in a TextContent block" (tools). Structured content is what lets a host's code, rather than its model, read an answer's role and filters. Model Context Protocol in Practice shows how the SDK builds the schema from a return type in return structured content with an output schema.

Every tool of the semantic server returns a ToolReply, a pydantic model with two fields: text, the text the in-process tool shows the model, and answer, the answer with its rows and provenance, or nothing when the result doesn't end the run. Failures take two routes. The MCP specification reports a tool execution error as a result with isError set, with "actionable feedback that language models can use to self-correct" (tools). A request with a misspelt dimension is that kind of failure, so the server raises the SDK's ToolError with chapter 6's validation message. A request the role may not make isn't, and the server returns it as an answer that declines, with a reason that starts "forbidden", as PolicyToolbox does in process. Each route is worth seeing from the host's side: the finance team's refund rate by region for fiscal 2026, the same with order_region for order__region, and the support team's net revenue for 2025.

tool-result-with-provenance.py Python 3.12.15 · anyio 4.16.0 · duckdb 2.0.0 · mcp 2.3.0 · pydantic 2.14.3 · pyyaml 6.0.3 · sqlglot 30.31.0 통과
"""What a host receives from query_metric: an answer with its provenance as structured content, a request the modelcan correct as a tool error, and a request the role may not make as an answer that declines. The `text block is the same JSON: yes` line settles thatthe finance answer's text matches its structured content, and `support, net revenue` with `is_error: False` and`answered: no` settles that a forbidden request declines rather than errors."""import jsonimport anyiofrom mcp import Clientfrom lib.semantic import loadfrom lib.semantic_server import build_serverfrom lib.warehouse import connectcon, layer = connect(), load()asks = {"finance, refund rate": ("finance", {"metrics": ["refund_rate"], "group_by": ["order__region"],                                             "filters": {"metric_time__fiscal_year": 2026}}),        "finance, misspelt dimension": ("finance", {"metrics": ["refund_rate"], "group_by": ["order_region"]}),        "support, net revenue": ("support", {"metrics": ["net_revenue"], "filters": {"metric_time__year": 2025}})}async def main():    for name, (role, request) in asks.items():        async with Client(build_server(role, shop=con, layer=layer)) as client:            tool = next(t for t in (await client.list_tools()).tools if t.name == "query_metric")            result = await client.call_tool("query_metric", request)        print(f"{name}, is_error: {result.is_error}")        if result.is_error:            print(f"{name}, text: {result.content[0].text}")            continue        answer = result.structured_content["answer"]        answered = answer["answered"]        assert answered == (role != "support")   # support may see no revenue, so its answer declines        print(f"{name}, answered: {'yes' if answered else 'no'}")        same = json.loads(result.content[0].text) == result.structured_content   # the specification asks for this JSON in the text block        assert same        print(f"{name}, text block is the same JSON: {'yes' if same else 'no'}")        if answer["answered"]:            print(f"{name}, rows: {', '.join(f'{region} {rate:.2%}' for region, rate in answer['rows'])}")            print(f"{name}, provenance fields: {', '.join(answer['provenance'])}")            print(f"{name}, provenance: {json.dumps({k: v for k, v in answer['provenance'].items() if k != 'sql'})}")        else:            print(f"{name}, reason: {answer['reason']}")    print(f"output schema requires: {', '.join(tool.output_schema['required'])}")anyio.run(main)
출력python tool-result-with-provenance.py
finance, refund rate, is_error: False
finance, refund rate, answered: yes
finance, refund rate, text block is the same JSON: yes
finance, refund rate, rows: AMER 7.11%, APAC 6.02%, EMEA 8.45%
finance, refund rate, provenance fields: source, metric, sql, filters, role, data_as_of
finance, refund rate, provenance: {"source": "metric", "metric": "refund_rate", "filters": {"metric_time__fiscal_year": 2026}, "role": "finance", "data_as_of": "2026-06-27 02:00:00"}
finance, misspelt dimension, is_error: True
finance, misspelt dimension, text: Error executing tool query_metric: error: request rejected: refund_rate can't use dimension 'order_region'; did you mean order__region?
support, net revenue, is_error: False
support, net revenue, answered: no
support, net revenue, text block is the same JSON: yes
support, net revenue, reason: forbidden: the support role may not see net_revenue
output schema requires: text, answer

A host's code can check each answer field by field. Finance's refund rates came back as structured rows, AMER 7.11%, APAC 6.02%, EMEA 8.45%, computed on finance's own database, whose copy of the calendar gives each day its fiscal year. The provenance has these fields: source, metric, sql, filters, role, data_as_of. Without the SQL, the provenance reads {"source": "metric", "metric": "refund_rate", "filters": {"metric_time__fiscal_year": 2026}, "role": "finance", "data_as_of": "2026-06-27 02:00:00"}. The text block carries the same JSON as the structured content, and the output schema requires text, answer.

The misspelt dimension came back with is_error set and the text "Error executing tool query_metric: error: request rejected: refund_rate can't use dimension 'order_region'; did you mean order__region?". The suggestion is chapter 6's, and the model can act on it. The words before it aren't the server's: the SDK's tool wrapper puts "Error executing tool" and the tool's name in front of the message of any ToolError a tool raises (mcp/server/mcpserver/tools/base.py). The in-process agent never showed the model that prefix, and Answer questions through a host measures what it changes.

Support's net revenue came back without is_error, as an answer that declines, with the reason "forbidden: the support role may not see net_revenue". We return a refusal as an answer, not an error, on purpose. An error invites the model to correct its request and try again, and there's no request support can correct into net revenue. A decline ends the run, as it did in chapter 9, and the host's code can see from the structured reason that the access rules, not the model, made the decision.

Working rule: Return a pydantic model from every tool, so that each answer travels as structured content with its rows, its role, its filters and its data's freshness, and a host's code can check them. Raise a tool error for a request the model can fix, with a message that says how. Return a refusal for access as an answer that declines, with its reason, so the host ends the run instead of letting the model try another way in.

서버를 메모리에서 테스트하기

마지막으로 변경된 판: 2026.11.12판

시맨틱 서버의 구조화된 응답은 필드 단위로 테스트할 수 있게 해 주며, 중요한 테스트는 접근에 관한 것이다. 한 역할을 위해 만든 서버는 다른 역할로 응답해서는 안 된다. 이런 테스트는 변경할 때마다 실행해야 하므로 포트나 프로세스가 필요하지 않아야 한다. Python SDK의 Client는 URL 대신 서버 객체를 넘기면 같은 프로세스 안의 서버에 연결하고, raise_exceptions=True는 도구 본문 밖에서 발생한 실패가 실제 메시지와 함께 돌아오게 한다. 이는 Model Context Protocol in Practice가 메모리에서 도구 테스트하기에서 설명한 내용이다. 같은 절에는 헤더와 출처 검사처럼 이런 테스트가 다룰 수 없는 것도 나열되어 있다.

서버의 각 테스트는 한 역할의 서버를 만들고, 메모리 내 클라이언트로 도구 하나를 호출한 뒤, 구조화된 콘텐츠를 검증한다. 테스트는 9장에서 측정한 규칙과 그 밑의 데이터베이스를 다룬다. EMEA 책임자는 gq-017의 골든 결과를 받는다. EMEA 책임자가 APAC을 요청하면 금지된 요청으로 거부된다. 책임자 서버 자체의 데이터베이스를 정책 없이 직접 조회하면 다른 지역의 주문이 하나도 들어 있지 않다. 지원 팀의 카탈로그는 매출을 읽는 지표를 모두, 그리고 그런 지표만 숨긴다. 마케팅의 작은 그룹은 억제된다. 철자가 틀린 차원은 올바른 차원을 제안하는 도구 오류가 된다. 이 책은 특정 테스트 러너를 정하지 않으므로, 파일은 lib/semantic_server.py에 있는 작은 도우미를 사용한다. pytest에서는 각 테스트가 평범한 비동기 테스트가 된다.

semantic-server-tests.py Python 3.12.15 · anyio 4.16.0 · duckdb 2.0.0 · mcp 2.3.0 · pydantic 2.14.3 · pyyaml 6.0.3 · sqlglot 30.31.0 통과
"""In-memory tests of the semantic server, one role per server, and one check that a test can fail. The prose'spoint rests on the final line: the lead's request on an analyst's server must differ from the lead's gold."""import anyiofrom lib.golden import golden_result, load_golden, results_matchfrom lib.semantic import loadfrom lib.semantic_server import build_server, call, run_testsfrom lib.warehouse import connectcon, layer = connect(), load()server = lambda role, region=None: build_server(role, region, con, layer)      # each on the role's own databasegold = golden_result(con, next(q for q in load_golden() if q.question_id == "gq-017"))lead_request = {"metrics": ["net_revenue"], "group_by": ["order__country"], "filters": {"metric_time__year": 2025}}HIDDEN_FROM_SUPPORT = {"average_order_value", "gross_revenue", "line_net_revenue", "net_revenue", "refund_rate"}async def test_lead_answer_matches_the_golden_result():    result = await call(server("regional_lead", "EMEA"), "query_metric", lead_request)    assert results_match(result.structured_content["answer"]["rows"], gold)async def test_lead_cannot_ask_for_another_region():    result = await call(server("regional_lead", "EMEA"), "query_metric", {"metrics": ["orders"],                        "filters": {"order__region": "APAC"}})    assert not result.is_error and result.structured_content["answer"]["reason"].startswith("forbidden")async def test_lead_database_holds_no_other_region():        # the policy layer bypassed: SQL straight to the database    regions = server("regional_lead", "EMEA").database.execute("SELECT DISTINCT region FROM analytics.fct_orders")    assert regions.fetchall() == [("EMEA",)]async def test_support_catalog_hides_every_revenue_metric():    listed = (await call(server("support"), "list_metrics", {})).structured_content["text"]    assert HIDDEN_FROM_SUPPORT == set(layer.metrics) - {line[2:].split(":")[0] for line in listed.splitlines()}async def test_marketing_small_groups_are_suppressed():    result = await call(server("marketing"), "query_metric", {"metrics": ["orders"], "group_by":                        ["order__channel", "order__country"], "filters": {"metric_time__month": "2026-06"}})    assert any("(under 10)" in row for row in result.structured_content["answer"]["rows"])async def test_unknown_dimension_is_a_tool_error_with_a_hint():    result = await call(server("finance"), "query_metric", {"metrics": ["orders"], "group_by": ["order_region"]})    assert result.is_error and "did you mean order__region?" in result.content[0].textasync def main():    passed = await run_tests(globals())    print(f"tests passed: {passed} of {passed}")    unbound = (await call(server("analyst"), "query_metric", lead_request)).structured_content["answer"]["rows"]    differs = not results_match(unbound, gold)   # the analyst's server returns every country, so the lead's gold must not match    assert differs    print(f"the lead's request on an analyst's server differs from the lead's gold: {'yes' if differs else 'no'}")anyio.run(main)
출력python semantic-server-tests.py
test_lead_answer_matches_the_golden_result: passed
test_lead_cannot_ask_for_another_region: passed
test_lead_database_holds_no_other_region: passed
test_support_catalog_hides_every_revenue_metric: passed
test_marketing_small_groups_are_suppressed: passed
test_unknown_dimension_is_a_tool_error_with_a_hint: passed
tests passed: 6 of 6
the lead's request on an analyst's server differs from the lead's gold: yes

실행 결과는 6 of 6를 보고한다. 통과한 테스트는 실패할 수 있을 때에만 가치가 있으므로, 이 실행은 첫 번째 테스트의 요청을 분석가의 서버에도 보내 그 결과를 책임자의 골든 결과와 비교한다. 분석가의 서버는 모든 국가를 반환하므로 결과는 책임자의 골든 결과와 다르며, 그래야 맞다. 따라서 첫 번째 테스트는 바인딩을 잃은 서버를 잡아낼 수 있다.

이 테스트들은 전송 계층이 아니라 서버를 검사한다. 테스트는 SDK의 인자 검증, 구조화된 출력, 오류 처리를 거치며, 오류 접두사도 여기서 나온다. 그러나 어떤 요청도 토큰을 싣지 않는다. HTTP 배포에서는 두 역할의 토큰을 보내 각각 자기 행을 받는지 확인하는 HTTP 테스트를 적어도 하나, 그리고 다른 서버를 위해 발급된 토큰을 보내 거부되는지 확인하는 테스트를 하나 추가한다.

작업 규칙: 각 역할의 규칙은 역할마다 서버 하나를 두고 구조화된 응답을 검증하는 메모리 내 클라이언트로 테스트하며, 바인딩이 잘못되었을 때 실패하는 검사를 포함한다. 골든 질문의 결과를 기댓값으로 사용해, 테스트와 점수가 무엇이 올바른 것인지에 대해 일치하도록 한다. 메모리 내 클라이언트가 보낼 수 없는 것에는 HTTP 테스트를 추가하되, 토큰을 먼저 다룬다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Answer questions through a host

마지막으로 변경된 판: 2026.11.15판

The tests show that the semantic server answers each tool call as the in-process agent would. The last question is whether an agent answers as well through it. A host is the application that runs the model and calls the server's tools for it, and the host here is the book's own: chapter 1's agent loop, run_agent() in lib/agent.py, with chapter 6's prompt and the recorded model, Qwen3-4B-Instruct-2507, that every chapter replays.

The only new piece is ServerToolbox in lib/semantic_server.py. ServerToolbox has the call() method the loop expects, and makes each call through an MCP client. ask_through_server() opens a client on a server and runs the loop in a worker thread, so that each tool call can reach the server on the event loop. For gq-017, the host made the calls list_metrics, query_metric: the first fills the prompt's catalog, and the second carries the model's request. A model's call that isn't a JSON object, or names a tool the server doesn't list, gets the in-process agent's message from the host without reaching the server, with the tools named in the in-process order. Model Context Protocol in Practice builds a general host in run the host loop; this one stays as thin as the book's loop.

Replay needs the model to see exactly what it saw when it was recorded, and over MCP it mostly does: the catalog and the prompt are the same, and so is every successful tool result's text. A tool error is the exception. Its text carries the SDK's prefix, so the model's next call has a prompt that no earlier recording holds. The recording mcp-host-runs, made with recordings/record_mcp_host.py, holds the replies to those calls only, from the same pinned model and settings. Every golden question runs twice, in process as chapter 9 measured it and through a server built for the question's role, and the example compares the two outcomes question by question.

host-asks-the-server.py Python 3.12.15 · anyio 4.16.0 · duckdb 2.0.0 · mcp 2.3.0 · pydantic 2.14.3 · pyyaml 6.0.3 · sqlglot 30.31.0 통과
"""The book's agent as an MCP host on every golden question, each tool on the asker's server, against chapter 9.The `same outcome as in process` line settles how many outcomes held, and the two questions that changed,`gq-013` and `gq-014`, each met a tool error."""from collections import Counterimport anyiofrom lib.agent import run_agentfrom lib.golden import golden_result, grade, load_goldenfrom lib.metric_tools import catalogfrom lib.model import RecordedModelsfrom lib.policies import PolicyLayer, PolicyToolbox, policy_forfrom lib.prompts import metrics_first_promptfrom lib.semantic import loadfrom lib.semantic_server import ask_through_server, build_serverfrom lib.warehouse import connectcon, layer = connect(), load()model = RecordedModels("metric-agent-runs", "policy-agent-runs", "mcp-host-runs")   # ch 11 recorded the restasync def main():    counts, changed, details, errors = Counter(), [], [], 0    for q in load_golden():        seen_as = PolicyLayer(layer, policy_for(q.role, q.region or None), con)        local = run_agent(q.question, metrics_first_prompt(catalog(seen_as)), model, PolicyToolbox(con, seen_as), 4)        trace, calls = await ask_through_server(build_server(q.role, q.region or None, con, layer), q.question, model)        outcomes = [grade(q, t.answer, golden_result(con, q)) for t in (local, trace)]        counts[q.split, q.kind, "questions"] += 1        counts[q.split, q.kind, "correct"] += outcomes[1] == "correct"        errors += any("is_error" in c for c in calls)        if outcomes[0] != outcomes[1]:            changed.append(f"{q.question_id} ({q.split}, {q.kind}): {outcomes[0]} in process, "                           f"{outcomes[1]} over MCP, by {trace.steps[-2].tool}")   # the last tool call ended the run            details += [f"{q.question_id} first request's filters: {trace.steps[0].arguments['filters']}",   # the model's first call                        f"{q.question_id} asked: {trace.answer.reason.splitlines()[0]}"]        if q.question_id == "gq-017":            print(f"gq-017 calls: {', '.join(calls)}")    for split in ("dev", "test"):        for kind in ("answer", "decline", "forbidden"):            print(f"{split} {kind} correct over MCP: {counts[split, kind, 'correct']} of "                  f"{counts[split, kind, 'questions']}")    print(f"runs with a tool error: {errors}")    total = len(load_golden())    print(f"same outcome as in process: {total - len(changed)} of {total}")    print("\n".join(changed + details) or "no outcome changed")   # one line per changed question, then detailsanyio.run(main)
출력python host-asks-the-server.py
gq-017 calls: list_metrics, query_metric
dev answer correct over MCP: 11 of 17
dev decline correct over MCP: 3 of 4
dev forbidden correct over MCP: 3 of 3
test answer correct over MCP: 6 of 17
test decline correct over MCP: 4 of 4
test forbidden correct over MCP: 3 of 3
runs with a tool error: 11
same outcome as in process: 46 of 48
gq-013 (dev, answer): correct in process, declined over MCP, by ask_back
gq-014 (dev, answer): correct in process, declined over MCP, by ask_back
gq-013 first request's filters: {'order__order_date': '2026-05'}
gq-013 asked: Are you looking for orders in the entire month of May 2026, or specifically on a single day in May 2026?
gq-014 first request's filters: {'order__order_date': '2026-05'}
gq-014 asked: Do you mean orders placed in the entire month of May 2026 or on a specific day in May 2026?

Through the server, the agent kept its in-process outcome on 46 of 48 questions. On the dev split's answer questions, the golden questions used while building, it scored 11 of 17, against 13 of 17 in process.

On the test split the score matched the in-process one: 6 of 17, against 6 of 17.

Every forbidden question was declined, 3 of 3 on dev and 3 of 3 on test, because the policy hides what the role may not see and refuses what it may not ask, as in chapter 9.

Only gq-013 and gq-014 changed, and both went through a tool error. 11 runs met one, and the rest kept their outcome. Both ask about orders in May 2026, and the model's first request had the filters {'order__order_date': '2026-05'}, which validation rejects with a hint to filter metric_time__month instead. In process, the model followed the hint and got the right count. Over MCP, it read the same hint after "Error executing tool query_metric:", and asked the person back instead: "Are you looking for orders in the entire month of May 2026, or specifically on a single day in May 2026?"

The printed line for gq-013 reads correct in process, declined over MCP, by ask_back, and gq-014's is the same. That's one sample per run at temperature 0.7, so it doesn't show that the prefix caused the change, only that a different text gave a different draw. It does show that an outcome can move with nothing changed but the transport's wording, and that only a score on the golden questions finds it.

Treat what the server returns as data in the host as well. OWASP's Top 10 for LLM applications lists an MCP server's output among the carriers of indirect prompt injection (OWASP, LLM01:2026), and a metric answer carries values from the warehouse, such as product names, that chapter 9 showed can hold instructions. The host shows the person the structured answer with its provenance, and never a model's retelling of it unchecked. Model Context Protocol in Practice covers the host's side in treat ticket text as untrusted data.

Working rule: Put the server under the host you already measured, and score it on the golden questions before anyone uses it, because the transport can change what the model reads. Compare outcomes question by question with the in-process runs, and read every run that changed. Record what the new text produces rather than editing the server's messages to match old recordings, and show people the structured answer with its provenance.

운영 환경에서 잘못되는 것

마지막으로 변경된 판: 2026.11.12판

MCP로 제공되는 시맨틱 계층의 위험은 가장자리에 있다. 누가 연결되어 있는지, 호스트가 그 밖에 무엇을 연결하는지, 어느 SDK가 서버를 대신해 응답하는지가 그것이다.

하나의 프로세스가 여러 사람에게 서비스한다. 하나의 역할에 묶인 stdio 서버는 한 사람의 호스트가 그 서버를 소유하는 동안에만 안전하다. 이 서버를 공유 프로세스로 감싸거나 토큰 없이 HTTP 뒤에 두면, 모든 사용자가 서버를 시작한 사람의 역할을 갖게 된다. 여기서 만든 시맨틱 서버는 감사 로그를 남기지 않으므로, 배포 환경에서는 응답마다 서버가 만들어진 대상 주체와 함께 9장의 항목을 기록해야 한다. 감사 항목에서 이를 알아챌 수 있다. 한 주체의 요청이 여러 사용자나 호스트에서 오거나, 한 사람이 보낼 수 없는 빈도로 들어온다. 둘 이상의 사람에게 서비스하려면 HTTP로만 제공하고, 역할은 각 요청의 토큰에서 가져와야 한다.

토큰의 역할과 정책 파일이 일치하지 않는다. roles.toml에 없는 역할을 지정한 클레임이나 지역이 없는 지역 책임자는 닫힌 상태로 실패해야 한다. policy_for()는 두 경우 모두 PolicyError를 발생시키며, 이를 잡아 기본 역할로 대체하는 서버는 역할 바인딩을 무효로 만든다. 클레임에서 역할로의 매핑은 모든 역할의 토큰과 역할이 없는 토큰으로 시험해야 한다.

서버의 연결이 역할보다 우선한다. 정책은 쿼리를 좁히지만, 쿼리가 닿는 범위는 데이터베이스가 결정한다. 책임자의 역할을 바인딩하고도 분석가의 연결로 쿼리하는 서버는 버그 하나만 있으면 유출로 이어진다. build_server()가 하듯이 역할을 바인딩할 때 그 역할 전용의 읽기 전용 데이터베이스를 열고, 테스트가 하듯이 그 연결이 다른 지역의 행을 읽을 수 없음을 테스트로 확인해야 한다.

호스트가 오래된 카탈로그를 캐시한다. 2026-07-28 개정판에서는 목록 결과에 유효 기간과 캐시 범위를 담을 수 있으므로 호스트가 이를 재사용할 수 있다(목록 결과 캐시하기). list_metrics는 도구 호출이므로 프로토콜은 그 카탈로그를 캐시하지 않지만, 호스트가 그래도 캐시하면 정책이 제거한 지표를 계속 보여 준다. 접근 규칙은 여전히 요청을 거부하므로, 모델이 스스로 거절했을 상황에서 금지(forbidden) 거절이 대신 나오는 정도의 비용만 든다.

SDK 업그레이드가 모델이 읽는 내용을 바꾼다. 도구 오류의 접두어는 서버의 코드가 아니라 SDK에서 오며, 인자 검증 오류의 문구도 마찬가지다. 새 릴리스가 둘 중 하나의 문구를 바꿀 수 있고, 그러면 오류 이후 에이전트의 동작도 달라진다. SDK의 버전을 고정하고, 업그레이드할 때마다 호스트를 통해 골든 질문을 다시 실행하며, 결과가 바뀐 실행을 읽어야 한다.

두 서버가 같은 지표를 설명한다. 공급업체도 MCP로 시맨틱 계층을 제공한다. dbt의 MCP 서버는 dbt 플랫폼의 프로젝트를 위해 list_metrics, get_dimensions, query_metrics 등의 이름을 가진 시맨틱 계층 도구를 제공하고(dbt Labs), Snowflake의 관리형 MCP 서버는 연결한 사용자의 기본 역할과 도구별 별도 권한을 사용해 Cortex Analyst를 통해 시맨틱 뷰에 대한 질문에 답한다(Snowflake). 이는 공급업체가 자사 제품을 직접 설명한 내용이다. 호스트가 공급업체의 서버와 여러분의 서버를 모두 연결하면, 그 모델에는 정의가 서로 다른 list_metrics 도구 두 개가 보인다. 호스트마다 시맨틱 계층당 서버를 하나만 연결하고, 둘이 꼭 필요하면 실전 Model Context Protocol이 서버 간 도구 이름 구분하기에서 설명하듯 도구 이름을 구분해야 한다.

이전 개정판의 클라이언트가 연결한다. mcp 2.3.0은 2025년 개정판의 클라이언트도 이전 핸드셰이크로 처리하며, dbt의 서버는 SDK의 1.x 계열에 고정되어 있다(dbt-mcp). 시맨틱 서버의 도구는 개정판에 의존하지 않지만, HTTP 배포의 세션과 취소는 의존한다. 실전 Model Context Protocol은 이를 전환 기간 동안 이전 클라이언트와 새 클라이언트 함께 지원하기에서 다룬다.

작업 규칙: 사람마다 stdio 서버를 하나씩 실행하거나, 각 요청의 토큰에서 역할을 가져오는 HTTP를 사용하고, 정책 파일이 모르는 클레임은 모두 닫힌 상태로 실패시킨다. 공유 데이터베이스가 아니라 역할 전용의 읽기 전용 데이터베이스로 쿼리한다. SDK의 버전을 고정하고, 바뀔 때마다 호스트를 통해 골든 질문을 다시 실행한다. 호스트마다 시맨틱 계층당 서버를 하나만 두고, 응답마다 감사 항목을 기록하며, 둘 이상의 사람이 공유하는 것으로 보이는 주체가 있는지 이를 읽어 확인한다.

이 장에서 내린 결정

이 책은 여기서 끝난다. 처음에 여러분은 스키마 위에서 SQL을 작성하는 에이전트에서 출발했고, 그 에이전트는 골든 질문 대부분에 오답을 냈다. 이제 여러분은 가게가 쓸 수 있는 버전을 만들 수 있다. 이 버전은 먼저 관리되는 지표에 묻고, SQL은 해당 역할의 읽기 전용 데이터베이스에서 가드 안에서만 작성하며, 답할 수 없으면 답을 거절하고, 각 역할이 볼 수 있는 범위 안에 머물게 하며, 이 모든 것을 MCP를 통해 어떤 호스트에든 제공한다. 무엇보다 여러분은 자신의 작업에서 작성한 골든 질문으로 변경 하나하나를 측정할 수 있으므로, 다음에 하는 변경은 증명할 수 있는 변경이 된다.

  • 시맨틱 서버는 6장의 도구 다섯 개를 제공한다. 각 도구는 9장의 PolicyToolbox를 얇게 호출하는 것이므로, 서버와 프로세스 내 에이전트는 같은 코드를 실행한다.
  • 모든 역할에 같은 도구 목록을 쓴다. 목록은 이름순이며 읽기 전용으로 표시한다. 역할은 list_metrics와 다른 도구가 반환하는 내용을 바꾼다.
  • 역할은 서버를 만들 때 결정된다. stdio에서는 환경에서, HTTP에서는 요청마다 검증된 토큰에서 가져온다. 어떤 도구도 role 인자를 받지 않는다.
  • 모든 서버는 해당 역할 전용의 읽기 전용 데이터베이스에 질의한다. 이 데이터베이스는 7장의 데이터베이스에 시맨틱 계층의 뷰와 달력을 더한 것이며, 정책은 두 번째 계층이다.
  • 모든 도구는 구조화된 콘텐츠를 반환한다. 모델에 보여 주는 텍스트와, 행과 출처를 갖춘 답이다.
  • 모델이 고칠 수 있는 요청은 도구 오류이고, 역할이 할 수 없는 요청은 거절하는 답이다. 거절하는 답의 이유는 "forbidden"으로 시작한다.
  • 서버는 메모리 안에서 서버당 역할 하나로 테스트한다. 골든 결과와 대조하며, 바인딩이 잘못되면 실패하는 검사를 포함한다.
  • HTTP 경로는 설명만 하고 실행하지 않는다. 예제는 소켓을 열지 않으며 메모리 내 클라이언트는 토큰을 싣지 않으므로, 검증된 토큰에서 역할로 가는 매핑은 HTTP 위에서 별도의 테스트가 필요하다.
  • 호스트는 이 책의 자체 루프와 프롬프트다. 앞선 녹화에 있는 호출은 재생하며, mcp-host-runs에는 SDK가 바꾼 오류 텍스트 뒤에 오는 호출만 담겨 있다.

이 판의 이 장

2026.11.15판예제 통과 2026년 11월 19이 장에서 5개 예제개 중 5개가 통과한다

영어판 2026.11.15판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

11장 중 11장: Serve the semantic layer over MCP

  1. Turn metrics into tools
  2. Carry the caller's role into every query
  3. Return answers with their provenance
  4. 서버를 메모리에서 테스트하기
  5. Answer questions through a host
  6. 운영 환경에서 잘못되는 것
  7. 이 장에서 내린 결정

맨 위로 돌아가기전체 장