AI로 번역함. 영어 원문을 사람이 검증함. 원문 읽기

실전 Model Context Protocol

교육 자료 키트

2026.11.19판으로, 책의 현재 판이다. 책이 바뀌면 함께 바뀐다. 출처를 밝히면 자유롭게 사용하고 수정할 수 있다.

강의 계획서

읽기 시간은 장의 본문 기준이다. 학습자는 Lab 또는 자신의 컴퓨터에서 예제도 실행한다.

주당 한 장: 12주

5주 후

학습 목표와 개요

각 장의 학습 목표는 첫 문장이다. 각 개요는 장의 절을 따르며, 절이 정의하는 용어, 예제가 실행되기 전에 요구하는 예측, 그리고 각 절이 끝나는 규칙을 담는다. 핵심 용어와 질문으로 제시되는 예측은 퀴즈 은행이 묻는 대로 영문판의 것이다.

1. MCP 처음부터 끝까지

읽는 데 약 53분, 5개 예제.

이 장을 마치면 기존 HTTP API를 stdio 기반 Model Context Protocol 서버 뒤에 두고, 클라이언트에서 그 서버의 도구를 호출하고, 둘이 주고받는 모든 메시지를 읽고, 작은 호스트를 통해 모델이 도구를 직접 고르게 할 수 있다. 모든 예제는 한 대의 컴퓨터에서 실행된다. 이 장의 설명은 사양의 2026-07-28 리비전과 Python SDK인 mcp 2.3.0에 대해 성립한다。

강의 개요: 7절
  1. 쇼핑몰과 그 API 살펴보기
    • 작업 규칙 이미 운영 중인 API를 감싸고, 그 API를 기준 시스템으로 유지한다. MCP 서버는 자체 자격 증명으로 API를 호출하고 응답을 변환하는 얇은 어댑터여야 한다. 그래야 API의 검증, 권한 부여, 로그가 모델뿐 아니라 모든 클라이언트에 대해 계속 동작한다. 감쌀 API가 없을 때만 데이터베이스 위에 직접 구축하며, 그 경우에도 비즈니스 규칙은 두 종류의 클라이언트가 함께 쓰는 한곳에 둔다.
  2. Wrap one endpoint as a tool
    • 작업 규칙 Start with one read-only tool for one endpoint, and write its docstring for a model: what it does, what its inputs look like, what it returns. Raise ToolError with a message that tells the model what to do differently, and let unexpected exceptions stay generic so internal details never leave the server. Past a handful of endpoints, shape the tools around the tasks the model has to do rather than one per endpoint (Shape tools around tasks, not endpoints).
  3. Call the tool from a client
    • 작업 규칙 Connect with mcp.Client, launch stdio servers with sys.executable and an explicit env=, and give the client a name. Pass each variable the server needs and nothing else from your environment, so no server sees secrets meant for another program. When a tool fails with only the SDK's generic message, read the server's standard error before you change the client.
  4. Read the messages on the wire
    • 핵심 용어 server/discover
    • 작업 규칙 When a call behaves unexpectedly, trace the wire before you read the SDK's code: a relay that copies and logs lines works with any client and any server. Never write to standard output from a stdio server, not even a debugging print(), because the client reads every line there as a message. Use logging, which the SDK sends to standard error, or write to standard error yourself.
  5. Let a model choose the tool
    • 작업 규칙 Keep the host's prompt and the parsing of the model's reply in your own code, and test the loop against recorded replies rather than a live model. Record the model's raw text, not SDK objects, so an SDK release doesn't invalidate a recording, and make a replay fail when its input changes. Switch to a live model only for the measurement runs that decide which descriptions and which model you ship.
  6. What goes wrong in production
    • 작업 규칙 On the machine that launches a stdio server in production, check three things: nothing but JSON-RPC reaches standard output, every variable the server needs is passed explicitly, and the server answers server/discover within 10 seconds of starting. Keep the server's standard error in your logs, because that is where its real errors go.
  7. 이 장에서 내린 결정

2. MCP가 API에 더하는 것

읽는 데 약 55분, 6개 예제.

이 장을 마치면 호스트, 클라이언트, 서버가 각각 무엇을 하는지 설명할 수 있다. 상점의 각 기능을 알맞은 Model Context Protocol 프리미티브에 배치할 수 있다. 모든 요청에 담기는 버전과 기능(capability)을 읽을 수 있다. 그리고 상점이 MCP 대신 일반 HTTP API를 유지해야 하는 경우를 판단할 수 있다. 이 장의 주장과 예제는 명세의 2026-07-28 개정판과 Python SDK인 mcp의 2.3.0 버전에 맞춘 것이다。

강의 개요: 11절
  1. 호스트, 클라이언트, 서버를 분리하라
    • 핵심 용어 host, client, capability
    • 작업 규칙 호스트에서 각 서버에 고유한 클라이언트를 하나씩 부여하고, 대화와 서버 사이를 넘나드는 모든 일은 서버가 아니라 호스트의 코드에 두어라. 모든 클라이언트는 서버가 무엇을 제공하는지 가정하지 말고 읽어 오는 것으로 시작하라. 그러면 서버가 도구를 바꾸어도 호스트가 깨지지 않는다. 서버를 작성할 때는 서버가 자신에게 보내진 요청만 볼 수 있다고 가정하라. 명세가 서버에 허용하는 것이 그것뿐이기 때문이다.
  2. 각 기능을 알맞은 프리미티브에 배치하기
  3. 도구는 모델이 선택하는 행동이다
    • 핵심 용어 tool
    • 작업 규칙 대화를 보고 사용할지를 모델이 결정해야 하는 기능은 도구로 만든다. 여기에는 고객이 쓴 내용에 따라 달라지는 조회가 포함되며, 환불처럼 무언가를 변경하는 모든 행동도 포함된다. 변경하는 행동은 호출 전에 호스트가 동의를 요청한다.
  4. 리소스는 애플리케이션이 선택하는 데이터다
    • 핵심 용어 resource
    • 작업 규칙 데이터가 필요한 때를 호스트 자체의 코드가 판단할 수 있다면 그 데이터를 리소스로 만든다. 알려진 종류의 티켓에 적용되는 정책이나 사용자가 열어 둔 레코드가 그런 예다. 대화를 읽는 모델만 필요 여부를 판단할 수 있다면 도구로 둔다.
  5. Prompts are templates the user chooses
    • 핵심 용어 prompt
    • 작업 규칙 Make a workflow a prompt when a person should start it and every run should follow the same steps, and keep the prompt's text on the server so that a change reaches every host at once. If no person chooses when it runs, it isn't a prompt: make the steps a tool, or put them in the host's own instructions.
  6. Carry the version and capabilities on every request
    • 작업 규칙 Read the version and the client's capabilities from each request, never from an earlier one, and answer -32021 when a call needs a capability the request didn't declare. Put the shop's own request metadata under its own reverse-DNS prefix, never under io.modelcontextprotocol/ or mcp. Log clientInfo and serverInfo for debugging, and decide nothing on them.
  7. Handle a version the server doesn't support
    • 작업 규칙 When a server answers -32022, pick the newest version in both your list and its supported list, retry once, and show the user an error naming both lists if they share none. Don't retry in a loop, and don't guess a version the server didn't list. On your own server, keep the supported list exact, because clients choose from it.
  8. 목록 결과 캐시하기
    • 작업 규칙 상점의 도구 목록처럼 모든 호출자에게 같은 목록에는 TTL과 "public" 범위를 설정하고, TTL은 배포 후 오래된 목록을 받아들일 수 있는 시간보다 길지 않게 고른다. 몇 시간이 아니라 몇 분 정도로 잡는다. 요청자가 누구인지에 따라 달라지는 것에는 SDK의 기본값인 "private"를 유지하고, cacheScope를 인가 검사의 대용으로 쓰지 않는다. 클라이언트에서는 기본 캐시를 유지한다. 이 캐시는 client.listen(tools_list_changed=True) 스트림에 변경 알림이 도착하면 항목을 버린다(mcp/client/client.py). 리소스가 바뀔 때 클라이언트에 알리기가 여는 스트림이 그런 종류다. 그 스트림이 없으면 어떤 알림도 클라이언트에 도달하지 않으므로 스트림을 열고, TTL로 폴링하는 대신 항목을 의심할 다른 이유가 있을 때 cache_mode="refresh"를 사용한다.
  9. Keep an HTTP API where MCP adds nothing
    • 작업 규칙 Keep a plain HTTP API for callers whose code knows which endpoint to call, such as other services, fixed workflows and batch jobs, and put an MCP server in front of the same API for hosts where a model or a user chooses at run time. Measure the overhead on your own transport before you route high-volume traffic through MCP, and pin the protocol version in clients you control, so they skip the discovery probe. Keep auto mode for clients that may meet servers you don't control, which may speak only the 2025 protocol.
  10. 운영 환경에서 문제가 생기는 경우
    • 작업 규칙 출시를 앞둔 서버에서는 네 가지를 확인한다. 각 기능의 프리미티브가 언제 실행할지 결정하는 주체와 맞는지, 클라이언트와 서버 사이의 어떤 것도 MCP 본문을 수정하지 않는지, clientInfo를 근거로 결정하는 것이 없는지, 그리고 모든 "public" 캐시 힌트가 호출자와 관계없이 같은 데이터에만 적용되는지다. 실패한 모든 요청의 프로토콜 버전과 오류 코드를 기록한다. 버전 오류와 엔벨로프 오류는 클라이언트나 게이트웨이가 바뀌었다는 첫 신호이기 때문이다.
  11. 이 장에서 내린 결정

3. 모델이 사용할 수 있는 도구 설계하기

읽는 데 약 58분, 8개 예제.

이 장을 마치면 상점의 API를 Model Context Protocol 도구로 바꿀 수 있다. 이때 도구의 이름, 설명, 입력 스키마, 결과, 오류는 모델이 그에 따라 행동할 수 있도록 만든다. 또한 설명 하나를 바꾸면 모델이 고르는 도구가 어떻게 달라지는지 측정할 수 있다. 이어지는 내용은 명세의 2026-07-28 개정판과 Python SDK인 mcp 2.3.0에 적용된다。

강의 개요: 10절
  1. Shape tools around tasks, not endpoints
    • 핵심 용어 Consent
    • 작업 규칙 Start from the tasks in your tickets or logs, not from your routes, and give each task one tool. Move every decision the model shouldn't make into the server, such as an amount or a sequence of calls. Use a handle when one task needs the result of another, state its lifetime in the description of the tool that creates it, make it unguessable, and check on every call that it belongs to the caller. Expose an endpoint as it stands only when the task and the endpoint are the same, as check_stock and GET /stock/{sku} are.
  2. 모델이 읽는 설명 작성하기
    • 먼저 묻기 Before you run it, predict how many first calls the vague set and the draft each get right.
    • 작업 규칙 설명은 두 문장에서 네 문장으로 쓴다. 도구가 무엇을 하는지, 가장 혼동되는 도구 대신 언제 이 도구를 쓰는지, 입력이 어떤 모습인지, 무엇을 반환하는지를 담는다. 여러 줄 docstring에 기대지 말고 description=로 넘겨서, 모델이 작성한 문구를 정확히 그대로 읽게 한다. 그런 다음 배포할 모델이 실제 티켓에서 도구를 고르는 과정을 녹화하고, 잘못된 선택을 읽고, 그 선택이 가리키는 설명을 고친다. 어느 변경이 효과가 있었는지 알아야 할 때는 녹화마다 한 가지만 바꾸고, 변경을 작성하는 데 쓰지 않은 티켓에서 결과를 확인한다.
  3. JSON Schema로 입력에 타입 지정하기
    • 작업 규칙 모든 인자의 타입을 API가 허용하는 한 좁게 지정한다. ID에는 패턴, 고정된 값에는 enum, 개수에는 범위, 날짜에는 형식을 쓴다. 코드가 실행되기 전에 SDK가 잘못된 호출을 거부하게 하고, 모든 실패를 한꺼번에 반환한다. 스키마에 의미를 맡기지 않는다. 유효한 날짜도 틀린 날짜일 수 있기 때문이다. 스키마가 표현하지 못하는 것은 도구 안에서 검사하고, 티켓에 자주 불완전하게 적히는 값은 어떻게 채우는지 설명에 적는다.
  4. 출력 스키마로 구조화된 콘텐츠 반환하기
    • 작업 규칙 모든 도구의 반환 타입으로 pydantic 모델을 지정하라. 그러면 SDK가 출력 스키마를 게시하고, 래퍼 없이 구조화된 콘텐츠를 반환하며, 텍스트 블록도 대신 추가한다. 호스트의 코드가 내리는 각 판단에 대해, 예컨대 within_limit처럼, 문장 속에 남겨 두지 말고 모델에 필드를 하나씩 두어라. 단순 문자열은 결과를 읽는 코드가 없는 도구에서만 반환하라.
  5. 실패를 도구 결과로 보고하기
    • 핵심 용어 protocol error, tool execution error
    • 작업 규칙 모델이 바로잡을 수 있는 모든 실패에는 ToolError를 발생시키고, 무엇이 잘못되었는지와 대신 무엇을 보내야 하는지를 메시지에 밝힌다. 유효한 값이 적다면 그 값도 포함한다. MCPError는 설정처럼 어떤 모델도 고칠 수 없는 실패에만 발생시키고, 예상치 못한 예외는 일반적인 메시지로 남겨 내부 세부 사항이 서버에 머물게 한다. 오류를 일반 문자열로 반환하지 않는다.
  6. 어노테이션으로 도구가 바꾸는 것을 표시하기
  7. 어노테이션은 보증이 아니라 힌트로 취급한다
    • 작업 규칙 모든 도구에 어노테이션을 붙인다. 힌트를 생략하면 신중한 호스트는 최악의 경우를 가정하기 때문이다. 도구를 멱등으로 표시하는 것은 서버가 이를 강제할 때만 하며, 환불, 결제처럼 한 번만 일어나야 하는 작업은 서버의 검사 뒤에 둔다. 호스트라면 신뢰하는 서버의 어노테이션은 사용자에게 무엇을 보여 줄지 결정하는 데만 사용하고, 동의 절차를 건너뛰어도 된다는 허가로는 절대 사용하지 않는다(부작용 전에 동의 구하기). 그 밖의 모든 서버의 어노테이션은 검증되지 않은 주장으로 취급한다.
  8. 도구 목록을 작게 유지한다
    • 작업 규칙 서버마다 하나의 사용자층과 그 사용자층의 작업에 필요한 소수의 도구만 두고, 목록이 호스트의 프롬프트에서 얼마나 드는지 측정한다. 토큰은 스키마와, 모델이 혼동하는 두 도구를 구분하는 문장에 쓰고, 스키마를 되풀이하는 설명 문구는 줄인다. 호스트에 필요한 도구가 모델이 잘 고를 수 있는 수보다 많다면, 한 서버의 목록이 연결에 따라 달라지게 하지 말고 도구를 여러 서버로 나눈 뒤 대화에 필요한 서버만 연결한다.
  9. 프로덕션에서 잘못되는 것
    • 작업 규칙 상점의 도구를 프로덕션에 배포하기 전에, 실제 티켓을 레이블링한 표본에서 배포할 모델이 도구를 선택하는 과정을 녹화하고, 모델이 바로잡을 수 있는 모든 실패가 유용한 메시지와 함께 ToolError로 반환되는지 확인하며, 각 출력 스키마에 계약 테스트를 적용한다. 배포 후에는 도구 선택 횟수, 인자에 나타나는 예제 값, 호스트의 RuntimeError를 관찰한다.
  10. Decisions this chapter made

4. 데이터를 리소스와 프롬프트로 제공하기

읽는 데 약 60분, 5개 예제.

이 장을 마치면 상점의 정책과 기록을 Model Context Protocol 리소스로 게시하고, 리소스 템플릿 하나로 많은 기록을 가리키고, 사용자가 인수를 입력하는 동안 그 인수를 완성하고, 리소스가 바뀌었을 때 클라이언트에 알리고, 환불 검토를 사용자가 고를 수 있는 프롬프트로 묶을 수 있다. 이 장의 주장과 그 뒤에 있는 코드는 Python SDK인 mcp 2.3.0에서, 사양의 2026-07-28 개정판을 기준으로 성립한다。

강의 개요: 8절
  1. Expose the policies as resources
    • 핵심 용어 annotations
    • 작업 규칙 Publish the documents a host should be able to put in front of a model as static resources, under a scheme that names your system, with a MIME type and a description the host can show. Use https:// only for resources the client can fetch without your server. Mark a result public only when every caller gets the same one, and give high priority only to the one or two documents every answer depends on, not to all of them.
  2. Address records with resource templates
    • 작업 규칙 Use a resource template for records that share one shape and an ID. Return the API's own JSON, and raise ResourceNotFoundError for a miss, which gives the client -32602 with the URI. Keep the scope private for anything that belongs to a user. Leave the SDK's ResourceSecurity on, and validate the variable's format yourself too. Exempt a variable from the check only when it must carry a path, and then check the path yourself.
  3. 사용자를 위한 인수 완성
    • 작업 규칙 인수 완성은 호출자가 읽을 수 있는 것만 대상으로 하며, 그 범위는 요청에 담긴 어떤 내용도 아니고 서버가 누구를 대리하는지로 정한다. 입력된 접두사에 따른 필터링은 SDK가 해 주지 않으므로 직접 하고, 목록은 100개 이내로 유지한다. 필터링한 원본 자체가 잘려 있었다면 항상 has_more을 설정하고, 일치하는 항목을 모두 세었을 때만 total을 보고한다. 접근할 수 없는 레코드에는 읽기와 완성 모두에서 존재하지 않는 레코드와 같은 not-found 응답을 준다.
  4. 리소스가 바뀌면 클라이언트에 알린다
    • 작업 규칙 호스트가 모델이나 사용자 앞에 내놓은 리소스만 감시하고, 각 이벤트는 새 값이 아니라 다시 읽으라는 신호로 취급한다. 스트림을 열 때마다, 즉 처음과 끊긴 뒤마다, 의존하는 모든 것을 다시 읽는다. 아무것도 재생되지 않기 때문이다. 클라이언트가 읽는 정확한 URI에 대한 업데이트를, 변경을 일으키는 코드 경로에서 발행한다.
  5. Package a workflow as a prompt
    • 작업 규칙 Offer a prompt for a procedure a person starts by name, and keep its arguments to values with a format you can check. Embed the resources the procedure depends on, so the host needn't fetch them. Validate every argument before you use it, and raise MCPError with INVALID_PARAMS for a bad one, because the SDK's own checks answer with an internal error.
  6. 리소스와 도구 중 선택하기
    • 작업 규칙 호스트가 레코드를 첨부하고 모델이 그 레코드를 조회한다면, 레코드를 리소스와 도구 양쪽으로 제공하고 둘을 하나의 코드 경로에서 처리하여 서로 어긋나지 않게 한다. 도구가 호스트가 보관할 만한 레코드를 찾았을 때는 내용 대신 해당 레코드에 대한 리소스 링크를 반환한다.
  7. What goes wrong in production
    • 작업 규칙 Test resources and prompts with two callers before they reach production. Neither may see, complete or watch the other's records, and neither should see a list change without a list-changed notification. Check that every resources/read of a user's data carries the private scope, and that a host recovers from a dropped stream by re-listening and re-reading.
  8. Decisions this chapter made

5. 호출 도중에 사용자에게 묻기

읽는 데 약 57분, 6개 예제.

이 장을 마치면 Model Context Protocol의 elicitation을 사용해, 쇼핑몰의 환불 도구가 호출 도중에 멈추고 호스트에 있는 사람에게 환불 확인을 요청한 뒤 그 답으로 이어서 처리하게 만들 수 있다. 이때 Multi Round-Trip Request 안에서 elicitation을 사용하며, 서버는 응답을 기다리는 동안 어떤 호출도 열어 두지 않는다. 이 장의 설명은 사양의 2026-07-28 리비전과 Python SDK인 mcp 2.3.0에 대해 성립한다。

강의 개요: 9절
  1. 상태 없는 서버가 답을 기다릴 수 없는 이유
    • 작업 규칙 클라이언트만 줄 수 있는 것을 도구 호출 안에서 기다리지 않는다. 고정된 개정판의 연결에서는 ctx.elicit()나 ctx.elicit_url()를 호출하는 모든 코드를 버그로 간주하고, 다음 절에서처럼 입력 요청을 반환한다. 기존 호출은 2025년 시기의 클라이언트에도 응답해야 하는 서버에만, 그것도 ctx.protocol_version 확인 뒤에서만 유지한다(기간 동안 기존 클라이언트와 새 클라이언트 함께 지원하기).
  2. Return an input request instead of a result
    • 작업 규칙 When a tool can't finish without the user, return an InputRequiredResult with one input request per question and a requestState that says what the retry must finish. Check the client's declared capabilities before you ask. Put in the state only what the tool needs to carry on, and let the SDK seal it. Make every side effect before the question either idempotent or harmless when no one answers, because the client may never call again.
  3. Resume the call with the answer
    • 작업 규칙 Use Client.call_tool with an elicitation callback in a host, and let the SDK run the rounds. Drive the loop yourself with client.session.call_tool(..., allow_input_required=True) only when the host must keep the state across a restart or show each round, and then repeat the arguments exactly. On the server, read the answer and the state together. When your server always sends a state, treat an answer that arrives without it, or with a state for another record, as a question never asked.
  4. 엘리시테이션으로 구조화된 입력 요청하기
    • 작업 규칙 호스트 앞의 사람만 줄 수 있는 답에는 폼 모드를 사용하고, 각 폼은 도구가 실제로 쓰는 몇 개의 필드로 제한하며, 답이 알려진 집합 중 하나인 곳에는 열거형을 사용한다. 폼은 리졸버와 pydantic 모델로 선언하고, 거절과 취소가 서로 다른 경로로 이어져야 할 때는 ElicitationResult를 받는다. 입력 요청은 상태를 직접 제어해야 할 때만 직접 만든다.
  5. 민감한 단계는 URL로 보낸다
    • 작업 규칙 비밀인 것과 사람을 다른 서비스에 로그인시키는 것은 모두 양식이 아니라 URL 모드로 보낸다. 흐름 자체의 ID를 requestState에 넣고, accept는 "사용자가 페이지로 갔다"는 뜻으로 취급하며, 재시도마다 흐름이 끝났는지를 서버 자신의 기록으로 판단한다. 흐름을 끝내는 사람이 흐름을 시작한 사람과 같은지 확인한다.
  6. 왕복 상태를 변조할 수 없게 유지한다
    • 작업 규칙 모든 requestState를 SDK가 봉인하게 하고, 돈, 접근 권한, 데이터와 관련된 상태에서는 봉인을 절대 끄지 않는다. 상태는 작고 불투명하게 유지한다. 레코드가 아니라 ID를 담는다. 한 번만 일어나야 하는 단계에는 답변 완료 상태의 기록을 서버에 직접 보관하고, 부수 효과가 일어난 뒤가 아니라 일어나기 전에 확인한다.
  7. Choose elicitation or a tool argument
    • 작업 규칙 Make a value a tool argument when the model can know it, and validate it in the tool. Elicit it when only the person can give it, or when the policy says a person must decide, and never accept that kind of value as an argument. Use URL mode for every secret. When you aren't sure, ask who would be at fault if the value were wrong.
  8. 운영 환경에서 무엇이 잘못되는가
    • 작업 규칙 질문을 하는 서버의 복제본에는 교체할 수 있는 공유 키 하나를 주고, 상태의 수명은 사람이 걸리는 시간에 맞추며, 견적 저장소와 한 번만 처리하는 모든 기록은 운영에 투입하기 전에 공유 저장소로 옮긴다. 전송 방식이 호출자를 제공하는 곳에서는 어디서든 각 질문을 호출자에 묶는다. 그런 다음 -32602는 기록된 사유별로, -32021은 호스트별로, 그리고 호출당 라운드 수를 관찰한다.
  9. 이 장에서 내린 결정

6. Streamable HTTP로 서빙하기

읽는 데 약 66분, 6개 예제.

이 장을 마치면 상점의 Model Context Protocol 서버를 Streamable HTTP로 서빙하고, 각 요청과 응답이 무엇을 담고 있는지 읽고, 오래 걸리는 호출의 진행 상황을 스트리밍하고 그 호출을 취소하고, 스티키 세션 없이 하나의 주소 뒤에서 서버를 복제본으로 실행하고, 브라우저가 속아서 보낸 요청을 거부할 수 있다. 이 장의 내용은 명세의 2026-07-28 리비전과 Python SDK인 mcp의 2.3.0 버전에서 성립한다。

강의 개요: 9절
  1. Move the server from stdio to HTTP
    • 작업 규칙 Serve over Streamable HTTP with MCPServer.run(transport="streamable-http") and its loopback default while you develop, and give clients the endpoint's URL. Leave stateless_http alone unless you also serve clients on a 2025 revision, where it decides whether they get sessions. Keep stdio for servers that a host launches for one user, as Choose stdio or Streamable HTTP explains.
  2. Read one HTTP exchange
    • 작업 규칙 When an HTTP call fails, read the exchange first: the three routing headers, _meta in the body, the status and the content type. Route in a gateway on Mcp-Method and Mcp-Name if you need to, and never rewrite a body without rewriting its headers to match, because the server will refuse the pair with -32020. On a server that supports only the pinned revision, a 405 means an older client is opening a GET stream; the SDK's app serves those clients instead.
  3. Stream progress on a long call
    • 핵심 용어 Progress
    • 작업 규칙 Report progress from any tool that can run longer than a few seconds, with a total when you know it and a message a person can read. Keep the SDK's default response mode. Use json_response=True only for a server whose every tool is quick, and know that it drops every progress report and every cancellation without telling anyone.
  4. 클라이언트에 더 이상 필요 없는 호출 취소하기
    • 작업 규칙 Streamable HTTP에서는 호출을 기다리는 태스크를 취소하거나 타임아웃을 사용해 호출을 취소하고, 스트림은 SDK가 닫게 한다. 긴 도구는 async def로 작성하고, 취소를 다시 발생시키며, await가 필요한 정리 작업은 보호된 범위 아래에 둔다. 오래 실행되는 모든 도구는 재시도해도 안전하게 만든다. 스트림이 끊어지면 호출이 사라지고 클라이언트가 이를 다시 보내기 때문이다.
  5. Run replicas without sticky sessions
    • 작업 규칙 Run replicas with no sticky sessions, and give every replica the same server name and the same requestState keys, injected from your secret store. Before you add a second replica, list every piece of state your tools keep in memory, such as handles, once-only records and subscriptions, and move each into storage that every replica reaches. Until one is moved, route the tools that depend on it to a single replica by Mcp-Name.
  6. Reject requests from other origins
    • 작업 규칙 Keep the SDK's loopback default on a developer's machine. When you deploy on any other address, pass transport_security=TransportSecuritySettings(allowed_hosts=[...], allowed_origins=[...]) with the names your server answers to, such as mcp.fernhill.example, and never rely on the default. Treat Origin validation as protection against browsers only, and put authorization in front of every server that anything but its own host can reach.
  7. stdio와 Streamable HTTP 중 선택하기
    • 작업 규칙 서버가 한 사용자의 컴퓨터에서 그 사용자를 대신해 동작한다면 stdio로 제공한다. 서버가 여러 호스트에 서비스하거나, 호스트가 접근할 수 없는 시스템을 보호하거나, 확장되어야 한다면 Streamable HTTP로 제공하고, 첫 외부 사용자가 생기기 전에 origin 검사와 인가를 갖춘다. 같은 서버 코드로 두 방식을 모두 제공할 수 있으므로, 서버별이 아니라 배포별로 선택한다.
  8. 운영 환경에서 발생하는 문제
    • 작업 규칙 상점의 서버가 어떤 주소에서 트래픽을 받기 전에, 실제 프록시 경로를 거쳐 네 가지를 시험한다. 외부 Origin가 403을 받는지, 호출이 실행되는 동안 진행 상황이 도착하는지, 프록시의 유휴 한도보다 긴 호출이 살아남는지, 호출의 스트림을 닫으면 도구가 멈추는지다. 그런 다음 421, 403, -32020을 클라이언트별로, 취소를 지속 시간별로 관찰한다.
  9. 이 장에서 내린 결정

7. 긴 작업을 태스크로 실행하기

읽는 데 약 65분, 4개 예제.

이 장을 마치면 Model Context Protocol 확장을 협상하고, 느린 재고 보충 보고서를 클라이언트가 폴링하는 태스크로 실행하고, 태스크를 만료시키거나 취소하고, MCP Apps가 도구에 무엇을 더하는지 설명할 수 있다. 이 장이 서술하는 내용은 명세 리비전 2026-07-28과 Python SDK인 mcp 2.3.0에 대해 성립한다。

강의 개요: 8절
  1. Negotiate an extension
    • 작업 규칙 Turn an extension on only on a side that implements it, through the SDK's extension classes, never by writing the identifier into capabilities by hand. Decide, for each tool on the server, what a client without the extension gets: an ordinary result when the work can finish within a normal call, and error -32021 when it can't. Check the client's declaration on every request, because at the pinned revision each request declares its own.
  2. Start a task instead of waiting
    • 작업 규칙 Answer with a task when the work can outlive the connection, and decide per call, not per tool, when some calls are short. Store the task before you return the handle, and generate its ID from a cryptographic random source, with at least 128 bits. Run the same code a plain call runs, so a task's result never differs from a plain result. Never return a task to a request that didn't declare the extension.
  3. Poll a task and fetch its result
    • 작업 규칙 Poll at the server's pollIntervalMs, re-read it on every reply, and stop at the first terminal status. Treat completed as the original call's result, isError and all, and failed as a protocol error. Hide the polling in a client extension so the rest of the host sees plain calls. When a host must survive a restart, store each task ID before the first poll, and resume from it.
  4. Expire and cancel tasks
    • 작업 규칙 Give every task a TTL that covers the longest wait you expect between the work finishing and the client fetching it, and purge after it; for the shop's restock report, that is an hour. Make long work check for cancellation at each natural step, such as each product, and clean up there. In the client, treat a cancel's acknowledgement as "asked", not "stopped", and treat -32602 from tasks/get as a task that is gone for good.
  5. MCP Apps가 더하는 것을 이해한다
    • 작업 규칙 결과를 가지고 행동하는 데 텍스트로는 부족하고(예: 정렬할 표, 행마다 하는 선택) 사용자가 쓰는 호스트가 이 확장을 지원할 때 MCP Apps를 사용한다. UI를 사용하는 모든 도구의 텍스트 결과를 완전하게 유지해, Apps가 없는 호스트가 뷰만 잃도록 한다. 모델이 앱 전용 도구를 호출하지 않아야 한다면 visibility를 ["app"]로 지정하고, 이를 강제하는 쪽은 서버가 아니라 호스트임을 기억한다.
  6. 작업 방식 선택: 태스크, 진행 상황 보고, 일반 호출
    • 작업 규칙 호스트와 서버 사이의 모든 타임아웃보다 충분히 빨리 결과가 돌아오면 일반 호출을 쓴다. 작업이 길고, 호출자가 계속 열려 있으리라 믿을 수 있는 연결에서 기다리며, 보여 줄 숫자를 원하면 진행 상황 보고를 쓴다. 작업이 연결보다 오래 지속될 수 있거나 호출자가 떠났다가 돌아오기를 원하면 태스크를 쓴다. 태스크는 상태 메시지만 보고한다는 점을 받아들이고, 확장이 없는 클라이언트를 위해 일반 호출 대체 경로를 두거나 명확한 -32021 오류를 반환한다.
  7. What goes wrong in production
    • 작업 규칙 Move tasks' storage to where every replica can read it before they go to production, record each task's owner and check it on every task request, and set a TTL with a purge that runs on a schedule. Then watch -32602 from tasks/get by replica, the ratio of tasks/get to tools/call, the number of stored tasks, and how long work runs after a cancel.
  8. Decisions this chapter made

8. Authorize clients with OAuth

읽는 데 약 81분, 7개 예제.

학습을 마치면 학습자는 protect the shop's Model Context Protocol server with OAuth 수 있다.

강의 개요: 9절
  1. Find the authorization server from the resource
    • 작업 규칙 Give every protected server an AuthSettings with its endpoint's URL as resource_server_url, exactly as clients will type it, and the smallest required_scopes that every request needs. Check the chain with one request that carries no token: a 401, a resource_metadata URL, metadata whose resource is the endpoint, and authorization server metadata whose issuer is the URL you fetched it from. When a value differs by a trailing slash or a port, fix the configuration rather than relaxing the client.
  2. 메타데이터 문서로 클라이언트 식별하기
    • 작업 규칙 모든 호스트에 안정적인 https:// URL의 Client ID Metadata Document를 하나씩 주고, 문서에는 호스트가 사용하는 리디렉션 URI만 담고 비밀은 넣지 않으며, 그 URL을 client_metadata_url로 SDK에 전달한다. 인가 서버가 발급한 사전 등록 자격 증명이 있으면 순위가 가장 높으므로 그것을 사용하고, Dynamic Client Registration은 다른 방법을 전혀 지원하지 않는 인가 서버에만 유지한다. 루프백 테스트에서는 클라이언트 ID를 https:// URL로 유지하고 테스트 인가 서버에서 이를 문서의 로컬 사본과 연결하며, 어떤 운영 서버도 받아들이지 않는 http:// ID를 클라이언트에 주지 않는다.
  3. PKCE로 토큰 받기
    • 작업 규칙 인가 코드 흐름은 SDK의 OAuthClientProvider가 실행하게 하고, 그것이 보내는 내용을 인가 서버 쪽에서 한 번 확인한다. 확인할 내용은 S256, state, 그리고 두 요청 모두에서 서버의 URL과 같은 resource이다. SDK가 건너뛰는 검사를 추가하여, 메타데이터에 S256를 나열하지 않는 인가 서버는 거부한다. 직접 운영하는 인가 서버에서는 S256만 받아들이고, 코드를 일회용이며 수명이 짧게 만들고, 각 코드를 해당 클라이언트, 리다이렉트 URI, 리소스에 묶는다.
  4. Bind each token to one server
    • 작업 규칙 Set validate_token_resource=True on every protected server, and make the token verifier fill AccessToken.resource from the token's aud. Treat an MCPDeprecationWarning from AuthSettings as a failed deployment, not as noise. Test the check with a token for another resource from the same authorization server, which must get 401. A server that calls another service on a client's behalf gets its own token for that service and never passes the client's token on (Never pass a client's token through).
  5. Validate the issuer of each response
    • 작업 규칙 Send iss from every authorization server you run, and advertise it with authorization_response_iss_parameter_supported: true, so that clients reject an answer without it. In a host, keep the SDK's check, add no normalisation around it, and treat a mismatch as an attack: show the user none of that response's error text. When a host must use an authorization server that doesn't send iss, keep the host to an allow-list of authorization servers, and refuse or warn the user about any server not on it. Don't count on a separate redirect URI per server when the host is identified by a metadata document.
  6. 토큰이 허용하는 스코프로 도구를 제한한다
    • 작업 규칙 모든 도구를 해당 스코프에 매핑하고, 헤더만으로 판단하지 말고 SDK가 인증하는 자격 증명 그대로 파싱된 요청을 인가한다. Authorization 헤더가 두 개인 요청과 맵이 다루지 않는 메서드는 거부한다. Mcp-Name는 디코딩한 뒤 본문과 일치해야 하는 힌트로 취급하고, 서버가 파싱하는 것과 똑같이 파싱할 수 없는 본문은 거부한다. 스코프가 없으면 해당 도구의 모든 스코프를 명시한 403 insufficient_scope 챌린지로 응답하고, required_scopes는 모든 요청에 필요한 것으로 한정한다.
  7. Ask for more scope when a call needs it
    • 작업 규칙 Let the SDK step up, and keep its union of scopes. List every tool a caller could gain by step-up, since a hidden tool never gets the 403 that starts it. In the host, compare the scope the token response granted with the scope the challenge asked for. When they differ, treat it as a decision, not a fault: tell the user which scope the call needs, and pass the ticket to someone who holds it. Never let an authorization server grant by step-up what a user's role doesn't allow. The client only asks, and the authorization server decides.
  8. What goes wrong in production
    • 작업 규칙 Run three probes against the deployment before the shop's server takes traffic. A request without a token gets 401 with a resource_metadata URL. A token for another resource gets 401. A refund with a read-only token gets 403 with scope="refunds:write", and the same refund with a second Authorization header gets 400. Then check the metadata of every authorization server your hosts use for S256, iss support and metadata document support, and watch the 401s, 403s and authorization requests per host.
  9. Decisions this chapter made

9. 도구를 오용으로부터 보호하기

읽는 데 약 60분, 6개 예제.

이 장을 마치면 Model Context Protocol 서버와 호스트 주위에 신뢰 경계를 그리고, 토큰 패스스루를 거부하고, 서버가 혼동된 대리인(confused deputy)으로 동작하지 않게 하고, 도구 정의를 고정해 변경된 정의를 잡아내고, 티켓 텍스트를 데이터로 취급하고, 부작용이 있는 모든 도구 호출 전에 사용자에게 확인을 구할 수 있다. 여기에서 다루는 모든 내용은 사양의 2026-07-28 리비전과 Python SDK인 mcp의 2.3.0 버전에서 유효하다。

강의 개요: 9절
  1. 신뢰 경계를 그린다
    • 작업 규칙 MCP 서버나 호스트를 배포하기 전에 경계 표를 작성한다. 데이터나 권한을 주고받는 당사자 쌍마다 한 행을 두고, 무엇이 넘나들며 누가 검사하는지 적는다. 검사 주체가 "모델"이나 "상대편"인 행은 빈틈이다. 직접 통제할 수 있는 검사로 그 빈틈을 메우고, 모델이 읽는 텍스트처럼 검사를 둘 수 없는 경우에는 그 뒤에 있는 도구가 할 수 있는 일을 제한한다.
  2. Never pass a client's token through
    • 작업 규칙 Accept only tokens whose audience is your server, and turn the check on explicitly, since the SDK doesn't by default. Call every upstream service with a credential of the server's own: an API key, a client-credentials token, or a token for the user from the upstream's own authorization server. Never forward the bearer token you received, even to a service that would accept it, and log the caller's identity yourself, because the upstream's logs will show only your server.
  3. Keep the server from acting as a confused deputy
    • 작업 규칙 Never take the acting user from a tool argument. Take it from the verified token's subject, together with the issuer whenever you accept more than one. Where customers sign in, the subject is the customer. Where staff sign in, it is the staff member, and the customer comes from the record the server looks up by ID and checks against what that person may handle. Check every record a call touches against it. Bind each handle your server issues to the user it was issued for, and answer another user's records and handles as not found. If your server proxies a third-party OAuth API, also follow the security guide's confused deputy section, and show your own consent page for each client before you forward anything.
  4. Catch poisoned tool descriptions
    • 먼저 묻기 Before you run the example, predict how many of the three poisoned runs call track_parcel.
    • 작업 규칙 Treat every definition from a server you don't operate as untrusted input to the model. When a user first enables a server, show the full definitions, not only titles, and look for free-text parameters the tool doesn't need, which are a poisoned description's channel. Don't count on the model or a scanner. Limit what each server can receive and each tool can do, and gate the calls.
  5. Pin tool definitions and flag changes
    • 작업 규칙 Pin every tool definition the user approves, by a hash over its name, title, description, schemas and annotations, per server. On a list-changed notification or a cache refresh, compare, keep any changed or new tool from the model, and show the user the difference before enabling it again. Accept that harmless rewordings ask again too: a definition the model reads is part of what the user agreed to.
  6. 티켓 텍스트를 신뢰할 수 없는 데이터로 취급한다
    • 작업 규칙 고객이 쓴 텍스트는 언젠가 지시로서 모델에 도달한다고 가정하고, 그 지시를 따르더라도 피해가 한정되도록 도구를 설계한다. 금액, 소유자, 한도는 서버 자체의 기록에서 가져오고, 텍스트를 보고 모델이 채우는 인자에서는 절대 가져오지 않는다. 부작용은 서버의 검사와 호스트의 동의 뒤에 둔다. 도구가 무시하는 인자는 기록으로 남긴다. 인자를 받지 않는 호출에 amount가 붙어 있다면 주입된 텍스트의 징후이기 때문이다.
  7. 부작용이 있는 호출 전에 동의를 구한다
    • 작업 규칙 호스트 자체의 부작용 없는 호출 목록에 없는 모든 도구 호출 전에 사용자에게 묻고, 그 목록은 어노테이션이 아니라 아는 바를 근거로 서버별로 만든다. 정확한 인자를 보여 주되, 사용자가 펼치면 전체를 보여 주고, 모든 결정을 호출과 함께 기록한다. 서버가 스스로 확인을 요청하더라도 동의는 호스트에 둔다. 신뢰하지 않는 서버는 묻지 않기 때문이다.
  8. 운영 환경에서 무엇이 잘못되는가
    • 작업 규칙 보안 통제는 운영 환경에 배포하기 전에 HTTP를 통해, 최소 두 사용자의 실제 토큰으로 테스트한다. 핸들 소유자는 모든 레플리카가 읽을 수 있는 곳에 저장하고, 토큰은 읽기 스코프로 시작하며, 서버가 호스트에 건네는 명령과 URL을 검증한다. 그런 다음 발급된 토큰과 실제로 사용된 스코프, 레플리카별 "견적 없음" 오류, 서버별 동의 질문 수, 사용자의 응답 속도를 지켜본다.
  9. 이 장에서 내린 결정

10. 티켓을 처리하는 호스트 만들기

읽는 데 약 72분, 6개 예제.

이 장을 마치면 호스트를 여러 Model Context Protocol 서버에 연결하고, 서버들의 도구에 충돌하지 않는 이름을 붙이고, 모델이 도구를 호출하고 그 결과를 읽는 짧은 루프를 실행하고, 서버의 입력 요청에 사용자를 대신해 응답하고, 리소스를 모델의 컨텍스트에 넣고, 이 모든 것을 거쳐 티켓 대기열을 처리할 수 있다. 이 장의 주장과 코드는 명세의 2026-07-28 리비전과 Python SDK인 mcp 2.3.0에서 성립한다。

강의 개요: 8절
  1. Connect one client per server
    • 작업 규칙 Give each server its own Client, in auto mode, under a key from the host's configuration. Cache each server's era for as long as its process or origin lasts, reuse it across restarts of the same configuration if you like, and probe again when a request fails with a version error. Don't use ClientSessionGroup at mcp 2.3.0: its connect_to_server speaks only the 2025 handshake, and given Client sessions it adds merged lists but not the retry rounds or the host's own names. Check again at each SDK release, because a group that probes would remove the need for your own map.
  2. Name tools across servers
    • 작업 규칙 Prefix every tool name with a key from the host's configuration, joined by . or _, and route each call back through your own map, never by serverInfo.name. Prefix all names, not only the ones that collide, so names stay stable when a server changes. Send an unknown or unprefixed name back to the model as an error instead of guessing.
  3. Run the host loop
    • 작업 규칙 Keep the loop in the host, short and bounded: route each call through your own map, pass it through consent, give it a timeout, and send every outcome back to the model, errors included, in a format your own code writes. Cap the model calls per ticket. Anything longer than a few turns, such as planning across tickets or memory, belongs in an agent framework, not in the host's protocol code.
  4. Answer input requests for the user
    • 작업 규칙 Give each client its own elicitation callback that knows which server it belongs to, and show the user that server's name with its message, the fields and a way to decline. Return a decline to the model as the server's error, not as silence, so the model can say what happened. Keep consent in the host as well, because the server's question covers only what the server chooses to ask.
  5. Put resources in the model's context
    • 작업 규칙 Decide in the host which resources reach the model, by rules you can state: a fixed list, or annotations from servers you trust, with a cap on their size. Read them through the client's cache. Let the user add a resource for one ticket when the rule misses it, and never let the model or a ticket's text choose on its own.
  6. Work through the ticket queue
    • 작업 규칙 Treat the model's last reply as a draft and the host's call log as what happened. Before a reply reaches a customer, compare its promises with the calls that ran, and send a ticket to a person when they differ, such as a refund ticket with no refund made. Strip any handle, such as a quote_id, from a reply before it goes out. Score a run on outcomes, not only on the first tool, and record a run of the whole queue each time you change the prompt, a description or the model.
  7. What goes wrong in production
    • 작업 규칙 Make the host log, per ticket, the tools offered, every call with its outcome, every consent question and input request, and the model's last reply, before it goes to production, so a bad answer can be traced to the turn that caused it. Watch the size of the tool list per model call, reconnect and retry on a lost call, and keep every server's tool list and pins under the host's control.
  8. 이 장에서 내린 결정

11. 서버를 테스트하고 실행을 관찰하기

읽는 데 약 68분, 6개 예제.

이 장을 마치면 Model Context Protocol 서버의 도구를 메모리 안에서와 HTTP를 통해 테스트하고, 클라이언트를 깨뜨릴 스키마 변경을 배포 전에 찾아내고, 기록된 호스트 실행을 회귀 테스트로 재생하고, OpenTelemetry로 도구 호출을 추적하고, 모델이 올바른 도구를 고르는 빈도를 측정하고, 도구를 사용하는 클라이언트를 깨뜨리지 않고 그 도구를 폐기할 수 있다. 여기서 프로토콜에 관한 설명은 명세의 2026-07-28 리비전 기준으로 성립하며, SDK에 관한 설명은 Python SDK인 mcp 2.3.0에 대해 성립한다。

강의 개요: 8절
  1. Test tools in memory
    • 작업 규칙 Test each tool in memory with Client(server, raise_exceptions=True), and assert on structured_content fields and is_error, not on whole results. Keep at least one test per transport you ship that goes over it on loopback, for the header, origin and streaming checks an in-memory test can't reach, and put the tests of trace propagation and list changes there too.
  2. Check schemas as a contract
    • 작업 규칙 Keep the last release's tools/list in the repository, and in CI validate every structured result your tests produce against it as well as against the new schema, each by the dialect it declares and by 2020-12 when it declares none. Treat a removed, renamed or retyped output field and a new required input as a breaking change: add the new field beside the old one, or add a new tool, and retire the old shape through a window (Change tools without breaking clients). Don't rely on a short TTL to protect clients that are already connected.
  3. Replay recorded host runs
    • 작업 규칙 Replay a recorded run of the whole queue in CI, assert on each ticket's tool sequence, and run a check that compares each reply's promises with the calls that returned a result. Keep generated IDs and clocks fixed in the servers a replay runs against, or it stops for reasons that aren't changes. Then treat RecordingMismatch as a signal, not as a flaky test: when you change a description, a prompt or a tool's output, record again with the recording script and compare the new run's scores with the old run's before you ship.
  4. Trace calls with OpenTelemetry
    • 작업 규칙 Install an OpenTelemetry SDK and exporter in every server and host you run, and let the SDK's middleware make the server spans. Build dashboards on the attributes the SDK emits, mcp.method.name, gen_ai.tool.name and error.type, and label them as following a Development-status convention at a named version, because the names may change. Don't validate method names against the pinned conventions package. Test propagation over a real transport, and wrap in-memory calls in a span of your own when a test needs a parent.
  5. 올바른 도구가 선택되는 빈도 측정하기
    • 작업 규칙 기록된 모든 실행을 전체 점수만이 아니라 태그별 첫 번째 도구로 채점하고, 인수는 티켓이 모델에 준 것과 실제 사실을 각각 기준으로 따로 채점한다. 가장 큰 혼동의 배후에 있는 설명부터 손보고, 다시 기록한 뒤 두 기록 사이에서 태그별 점수를 비교한다. 모든 점수 옆에 모델, 프롬프트, 티켓 집합을 밝히고, 서로 다른 설정의 점수끼리는 결코 비교하지 않는다.
  6. Change tools without breaking clients
    • 작업 규칙 Retire a tool in three releases: add the replacement and mark the old tool deprecated in its description, keep both working through a window you announce, then answer the old name with an execution error that names the replacement. Shorten ttlMs on tools/list while the change is under way, publish a list change at each release, and open a subscriptions/listen stream in every host you control. Say in your changelog that the window is your policy, since the protocol defines none.
  7. 프로덕션에서 무엇이 잘못되는가
    • 작업 규칙 트레이스나 점수에 의존하기 전에 그것이 무엇을 포괄하는지 확인한다. 어느 전송 방식인지, 어느 모델인지, 각 스키마의 어느 릴리스인지를 따진다. 스팬 이름은 개수가 한정되도록 유지하고 인자는 기본적으로 스팬에 넣지 않으며, 대시보드가 쓰는 속성 이름은 이름이 붙은 규약 버전에 고정한다. 그리고 모든 릴리스가 레플리카에 도달하기 전에 계약 테스트와 리플레이를 실행한다.
  8. 이 장에서 내린 결정

12. 2025년형 서버 마이그레이션

읽는 데 약 66분, 6개 예제.

이 장을 마치면 2025년 개정판과 Python SDK 1.x 계열에 맞춰 작성한 Model Context Protocol 서버를 2026-07-28 개정판 사양과 mcp 2.3.0으로 옮길 수 있다. 대상에 관한 설명은 해당 개정판과 SDK 버전에서만 성립한다. 서버가 무엇에 의존하는지 찾아내고, 세션을 제거하고, HTTP+SSE 전송에서 벗어나게 하고, 샘플링, 루트, 로깅, 동적 클라이언트 등록(Dynamic Client Registration)을 대체하고, 코드를 이식한다. 그리고 옛 클라이언트가 남아 있는 동안 두 시대의 클라이언트를 모두 지원한다。

강의 개요: 9절
  1. Inventory what the old server depends on
    • 작업 규칙 Inventory before you change anything, and sort the list by status. Fix every removed dependency before you let a client at the pinned revision connect, because there is no window for it, and count every request the server pushes mid-call as removed, even when the feature it asks for is only deprecated. Give each deprecated one a date of your own, earlier than the registry's earliest removal, and don't wait for warnings: run a scan like this one in CI, because the SDK is silent about some deprecated features.
  2. initialize와 세션 ID 제거하기
    • 작업 규칙 낡은 서버에서 세션, 세션 ID, 연결별로 저장된 모든 것의 사용처를 찾아, 각 상태를 한 도구가 반환하고 다음 도구가 인자로 받는 핸들로 바꾼다. 핸들은 불투명하게 만들고, 이를 만드는 도구의 설명에 명시한 만료 시간을 부여하며, 호출마다 호출자가 사용할 수 있는지 확인하고, 모든 복제본이 읽을 수 있는 곳에 저장한다. 이후 호출에 필요한 것은 세션을 키로 하는 딕셔너리에 두지 않는다. 세션을 아직 사용하는 2025년 시기의 클라이언트에 대해서도 마찬가지다.
  3. HTTP+SSE에서 Streamable HTTP로 옮기기
    • 작업 규칙 로그에 HTTP+SSE를 아직 쓰는 호스트가 보이지 않으면, 서버의 HTTP+SSE 전송 방식은 포팅하지 말고 삭제한다. 쓰는 호스트가 있다면 Streamable HTTP 엔드포인트 옆에 옛 엔드포인트를 두고, 이 엔드포인트로 들어오는 모든 연결을 클라이언트별로 기록하며, 제거 날짜를 정해 각 호스트의 소유자에게 알린다. 이 전송 방식의 기간은 12개월이 아니라 3개월이었으므로, 이미 제거 대상이 된 것으로 간주한다.
  4. Replace sampling, roots and logging
    • 작업 규칙 Move every pushed elicitation into a resolver, which serves both eras. Delete sampling rather than move it: let the host's model do model work, or call a provider from the server with the server's own credentials. Turn roots into a parameter checked against an allow-list in the server's configuration, and send log lines to stderr and your traces, never to the client.
  5. Replace dynamic client registration
    • 작업 규칙 Publish a Client ID Metadata Document for every host and pass its URL as client_metadata_url. Make every authorization server you run advertise support for it, keep its registration endpoint only until the hosts that need it have moved, and log which kind of client ID each token was issued to, so that you can see when registration traffic has stopped.
  6. Port the code from SDK 1.x to 2.x
    • 작업 규칙 Keep a 2025-era server pinned to mcp<2 until its port passes its tests, then port in one change: the imports and renames the errors point at, then each silent break from the migration guide, checked with a test against what a client sees. Pin the 2.x release exactly afterwards, and treat each 2.x release as a change to test, since the SDK's warnings and defaults move between releases.
  7. Serve old and new clients through the window
    • 작업 규칙 Serve both eras from one streamable_http_app() through the window, write every question a tool asks as a resolver, and route requests that carry Mcp-Session-Id to the replica that minted it. Count requests by era. When the 2025 count has stayed at zero for as long as your slowest host takes to upgrade, serve the pinned revision only, and answer initialize with an error that names the versions you support, as the specification asks.
  8. What goes wrong in production
    • 작업 규칙 Prove the port through the real proxy path before it takes traffic, with four tests: a 2025 client completes a confirmation, a 2026 client completes the same one, a 2025 session survives a deployment, and the version header reaches the server. Then watch requests by era, 404s by client and every deprecation warning, until the 2025 count reaches zero.
  9. 이 장에서 내린 결정

퀴즈 모음

인증된 교육자를 위해 모든 장의 질문과 정답 해설을 제공한다. 각 답은 해당 절과 연결된다. 증명을 얻는 방법