05편에서 model 밖의 검색을 분리했다. 마지막 글은 pretrained model을 목적에 맞게 조정하는 objective와, model이 tool을 고르고 protocol을 거쳐 실행하는 system을 분리한다.
가장 먼저 바로잡을 문장은 이것이다.
MCP는 LLM 학습 algorithm, RAG algorithm, agent reasoning algorithm이 아니다. MCP는 AI application과 server가 context와 action을 교환하는 protocol이다. model이 tool을 선택하는 확률과 tool이 JSON-RPC로 실행되는 계약은 서로 다른 계층이다.
Pretraining과 fine-tuning의 공통 objective
causal language model은 다음 token negative log-likelihood를 줄인다.
pretraining과 SFT 모두 식의 뼈대는 같다. 달라지는 것은 data distribution, loss mask, parameter update 범위다.
- pretraining — 대규모 text의 다음 token
- SFT — instruction과 desired response
- domain adaptation — domain corpus 또는 labeled task data
- continued pretraining — domain raw text의 LM objective
목적이 다른데 모두 “fine-tuning”이라고 부르면 dataset과 loss를 놓친다.
Supervised fine-tuning
prompt 와 target response 가 있을 때
이다.
Loss mask
conversation 전체를 concatenate해도 assistant response token에만 loss를 줄 수 있다.
인 token이 system, user, assistant 중 어디인지 dataset collator에서 확인한다.
Sequence weighting
모든 token loss를 평균하면 긴 response가 더 많은 항을 가진다. sequence별 평균 뒤 sample 평균을 내면 각 sequence weight가 같아진다.
Token mean은
Sequence mean은
이다. 두 reduction은 긴 sample 비중을 다르게 만든다.
Teacher forcing과 exposure gap
training에서는 target prefix 를 조건으로 쓰지만 inference에서는 model이 생성한 prefix를 쓴다. 한 번의 오류가 이후 distribution을 바꿀 수 있다. SFT loss 감소만으로 multi-turn rollout 성공을 보장하지 않는다.
Full fine-tuning과 PEFT
Full fine-tuning
모든 parameter 를 update한다. optimizer는 parameter 외에 gradient와 moment state를 유지하므로 training memory가 weight file 크기보다 훨씬 크다.
Adam 계열의 단순 element accounting은 parameter당 다음을 포함할 수 있다.
- model weight
- gradient
- first moment
- second moment
- mixed precision master weight
정확한 byte는 dtype, sharding, offload와 optimizer 구현에 따라 달라진다.
Parameter-efficient fine-tuning
base weight 대부분을 freeze하고 작은 parameter 집합 만 학습한다.
memory와 checkpoint 수를 줄이지만 forward에서 base model은 여전히 필요하다. trainable parameter가 1%라고 inference compute가 1%가 되는 것은 아니다.
LoRA
weight 를 freeze하고
를 학습한다.
forward는
이다. scaling을 포함하면 흔한 형태는
다. library마다 scaling convention과 initialization이 다를 수 있다.
Parameter 수
full matrix는
이다. rank 가 작을수록 parameter가 줄지만 update space도 제한된다.
Merge
inference 전에
로 합치면 추가 matmul 없이 실행할 수 있다. quantized base에 merge할 때 dequantization, re-quantization과 precision loss 조건을 확인해야 한다.
LoRA가 뜻하지 않는 것
- base weight 자체가 low rank라는 뜻이 아니다.
- final model 전체가 rank 이라는 뜻이 아니다.
- 모든 task update에 작은 rank가 충분하다는 보장이 아니다.
- 같은 rank라도 target module 수가 다르면 parameter 수가 다르다.
QLoRA의 경계
QLoRA는 frozen pretrained model을 4-bit로 quantize해 memory를 줄이고 LoRA adapter를 학습하는 방법을 제시했다. 핵심 요소로 4-bit NormalFloat, double quantization, paged optimizer를 사용했다.
개념적으로 forward는 quantized storage 를 compute dtype으로 dequantize해 base path를 계산하고 LoRA path를 더한다.
4-bit storage가 gradient, activation, LoRA weight, accumulator까지 모두 4-bit라는 뜻은 아니다. checkpoint memory, runtime memory와 optimizer memory를 나눠 본다.
Prompt tuning과 adapter
Soft prompt
trainable vector 를 input embedding 앞에 붙인다.
base model weight는 freeze한다. prompt token 수 만큼 context와 attention 비용이 늘어난다.
Adapter
layer 안에 bottleneck module을 추가한다.
LoRA가 weight update를 low-rank path로 표현하는 것과 architecture에 별도 activation module을 넣는 adapter는 같지 않다.
Knowledge distillation
teacher distribution 를 student 가 따라가게 한다.
큰 temperature 는 class 간 relative probability를 부드럽게 드러낸다. scaling은 gradient scale을 보정한다.
hard target cross-entropy와 섞을 수 있다.
teacher의 오류와 bias도 전달될 수 있다. student가 작아졌다고 특정 hardware에서 latency가 정확히 parameter 비율만큼 줄지는 않는다.
Preference data
prompt 에 대해 chosen response 와 rejected response 가 있다고 하자.
preference는 절대 정답 label이 아니라 두 응답의 상대 순서다. annotator disagreement와 order bias를 포함할 수 있다.
Reward model과 Bradley-Terry
response에 scalar reward 를 준다. chosen이 preferred일 probability를
로 둔다.
reward model loss는
이다. 두 reward에 같은 상수를 더해도 차이는 같아 preference probability가 변하지 않는다. reward의 absolute zero는 식에서 식별되지 않는다.
RLHF objective의 뼈대
정책 가 높은 reward를 얻되 reference policy 에서 너무 멀어지지 않게 한다.
- reward 항 — preference model이 좋아하는 output
- KL 항 — reference에서 과도하게 벗어나는 것을 제한
- — tradeoff
실제 PPO-based RLHF에는 value model, advantage estimation, clipping과 rollout sampling이 추가된다. 위 식은 목적의 뼈대다.
Reward hacking
학습은 진짜 인간 효용이 아니라 learned reward를 최대화한다. reward model의 빈틈을 이용해 score만 높이는 output이 생길 수 있다.
proxy optimization의 문제다. held-out human evaluation과 adversarial audit가 필요하다.
DPO
DPO는 KL-constrained reward optimization과 Bradley-Terry preference model을 재parameterize해 별도 reward model과 online RL 없이 classification-like loss를 만든다.
model과 reference의 log probability ratio를
로 본다.
loss는
이다.
식을 네 조각으로 읽는다
model이 reference 대비 chosen probability를 rejected보다 더 올리면 가 커지고 loss가 작아진다.
Sequence log probability
response length가 합에 영향을 준다. implementation의 masking, padding, averaging 여부를 확인한다. 논문 objective와 library의 length normalization 변형이 같지 않을 수 있다.
를 temperature 하나로만 부르지 않는다
DPO 유도에서 는 reference policy에서 벗어나는 정도와 연결된다. 구현과 논문에 따라 해석과 tuning range가 다르므로 “클수록 무조건 alignment가 강하다”처럼 단정하지 않는다.
SFT, RLHF, DPO가 답하는 질문
| 방식 | data | 직접 줄이는 것 |
|---|---|---|
| SFT | prompt와 target response | target token NLL |
| Reward model | response pair와 preference | pairwise preference classification loss |
| PPO-RLHF | rollout과 learned reward | KL 제약 아래 expected reward |
| DPO | chosen/rejected pair와 reference | preference log-ratio classification loss |
preference optimization이 factual knowledge를 자동 추가하지 않는다. 선호 dataset에 없는 최신 사실은 RAG, tool 또는 새 data가 필요하다.
Agent를 확률적 policy로 본다
state 또는 context 에서 action 를 선택한다.
action은 다음 중 하나일 수 있다.
- text token을 계속 생성
- tool을 선택
- tool argument 생성
- 사용자에게 질문
- 종료
LLM agent framework가 반드시 formal reinforcement learning policy를 학습한다는 뜻은 아니다. API model의 token distribution을 workflow가 action으로 해석할 수 있다는 분석 관점이다.
Tool 선택과 argument 생성
tool 목록이 라면 tool choice를 categorical distribution으로 볼 수 있다.
argument JSON은 token sequence다.
schema-constrained decoding은 허용되지 않은 token을 mask해 valid language 안에서 sampling하도록 할 수 있다. schema validation은 model probability와 별도다.
model이 tool을 골랐는가
≠ argument JSON 문법이 valid한가
≠ argument 의미가 올바른가
≠ tool 실행이 성공했는가
≠ 결과가 사용자 목표를 달성했는가
각 단계의 성공률을 따로 잰다.
Expected utility
action 의 결과 와 utility 가 있을 때
안전 비용과 latency를 포함한 단순 score는
처럼 쓸 수 있다.
실제 model이 이 식을 명시적으로 계산한다는 뜻이 아니다. workflow에서 “정확도만 높은 tool” 대신 비용·지연·위험을 함께 비교하기 위한 설계식이다.
Multi-step success probability
단계 가 이전 단계 성공 조건에서 성공할 probability를 라 하면 전체 성공은
이다.
각 단계가 95% 성공하고 10단계가 조건부로 이어진다고 단순화하면
약 59.9%다. 긴 agent loop에서 작은 failure가 누적되는 이유다. 실제 단계는 independent하지 않으므로 unconditional 를 단순 곱하면 안 되고 conditional rate를 측정해야 한다.
Retry
한 번의 독립 실행 성공 probability가 이고 최대 번 시도하면 적어도 한 번 성공할 probability는
이다. , 3회면
이다.
하지만 실제 retry는 independent하지 않을 수 있다. 같은 invalid argument를 그대로 재시도하면 실패 원인이 반복된다. write tool의 retry는 duplicate side effect를 만들 수 있어 idempotency key와 상태 확인이 먼저다.
Latency의 합과 max
sequential tool chain은
parallel branch는 join 시점에
가 critical path다. 여기에 orchestration overhead가 더해진다.
percentile은 단순히 더할 수 없다. 각 component의 p95를 합한 값이 전체 p95와 같지 않다. request trace에서 end-to-end distribution을 직접 측정한다.
Agent 평가
Task success
최종 목표 달성 여부다. exact match가 어려우면 deterministic checker, environment state, human rubric를 사용한다.
Tool selection accuracy
class imbalance가 크면 macro F1과 confusion matrix를 같이 본다.
Argument validity와 semantic correctness
- JSON parse rate
- schema validation rate
- required field accuracy
- value exactness 또는 tolerance
- forbidden field rate
schema-valid하다고 업무 의미가 맞는 것은 아니다.
Trajectory efficiency
같은 heuristic을 쓸 수 있다. minimum step 정의가 애매하면 tool call 수, token, latency, cost를 각각 보고한다.
Safety
- destructive action confirmation rate
- unauthorized access attempt rate
- secret exposure rate
- prompt injection success rate
- tool output trust boundary 위반
평균 task score에 섞지 않고 blocking metric으로 둘 수 있다.
Binomial confidence interval의 필요
100개 task에서 80개 성공한 observed rate는 0.8이다.
sample이 바뀌면 값도 바뀐다. simple standard error 근사는
이다.
95% normal approximation은 약 , 즉 이다. 작은 sample이나 극단 probability에는 Wilson interval 같은 방법이 낫다.
80%와 83%를 한 번 측정하고 개선이라고 단정하기 전에 paired task 결과와 confidence interval을 본다.
MCP가 정의하는 것
2026-07-21에 공식 site의 latest redirect를 확인한 revision은 2025-11-25다. 이 revision 기준 MCP는 JSON-RPC 위의 stateful protocol이며 host-client-server architecture를 둔다.
Host
AI application의 container와 coordinator다.
- 여러 client instance 생성과 관리
- connection permission과 lifecycle
- security policy와 사용자 동의
- LLM integration과 context aggregation
Client
host가 server마다 만든다. 한 client는 특정 server와 one-to-one connection을 유지한다.
- protocol version과 capability negotiation
- message routing
- subscription과 notification
- server 사이의 isolation
Server
focused capability를 노출한다.
- prompts
- resources
- tools
- client sampling 또는 elicitation 요청
server가 전체 conversation과 다른 server를 자동으로 볼 수 있는 구조가 아니다. host가 security boundary와 context 전달을 통제한다.
MCP server primitive의 control model
2025-11-25 명세는 server primitive를 다음처럼 구분한다.
| Primitive | 주된 control | 역할 |
|---|---|---|
| Prompts | user-controlled | 사용자가 고르는 재사용 template |
| Resources | application-controlled | file, record 같은 context data |
| Tools | model-controlled | 실행 가능한 function |
model-controlled은 사용자 확인이 필요 없다는 뜻이 아니다. client UI와 host policy가 sensitive operation에 consent를 요구해야 한다.
MCP 최신 명세에는 server primitive 외에도 client feature인 roots, sampling, elicitation과 tasks 같은 기능이 있다. capability가 선언됐을 때만 해당 operation을 사용한다.
MCP base protocol
모든 message는 JSON-RPC 2.0 형식을 따른다.
Request
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list",
"params": {}
}
request는 string 또는 integer id를 포함하고 같은 session에서 requestor가 이전에 쓴 ID를 재사용하면 안 된다.
Result response
{
"jsonrpc": "2.0",
"id": 1,
"result": {}
}
request와 같은 ID로 correlation한다.
Error response
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32602,
"message": "Invalid params"
}
}
Notification
{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}
notification은 ID가 없고 receiver가 response를 보내지 않는다.
MCP lifecycle
Initialization
첫 interaction은 initialize request여야 한다. client는 다음을 보낸다.
- supported protocol version
- client capabilities
- client implementation info
server는 negotiated version, server capabilities, server info로 응답한다. 성공 뒤 client가 notifications/initialized를 보낸다.
Operation
negotiated capability 범위에서 tool, resource, prompt와 client feature를 사용한다. 구현한 feature를 capability에 광고하지 않았으면 사용하면 안 된다.
Shutdown
transport에 맞는 graceful termination을 따른다. timeout, cancellation과 outstanding request 처리 정책을 구현한다.
이 lifecycle은 수학이 아니라 finite-state protocol contract다. 상태 전이를 지키지 않으면 model 품질과 무관하게 interoperability가 깨진다.
JSON Schema와 validation
2025-11-25 base protocol은 schema에 $schema가 없으면 JSON Schema 2020-12를 default로 두고, client와 server가 최소 2020-12를 지원하도록 요구한다.
tool input schema 예시는
{
"type": "object",
"properties": {
"query": { "type": "string", "minLength": 1 },
"limit": { "type": "integer", "minimum": 1, "maximum": 20 }
},
"required": ["query"],
"additionalProperties": false
}
이다.
validation은 다음을 보장하지 않는다.
query가 업무적으로 올바름- 사용자가 이 data에 접근 가능함
- read tool이 실제로 side effect 없음
- output이 prompt injection을 포함하지 않음
syntax, semantics, authorization, side effect를 분리한다.
Tool contract에 필요한 것
명확한 이름과 description
model은 tool metadata를 context로 읽고 선택한다. 비슷한 tool 이름과 겹치는 description은 classification ambiguity를 만든다.
좁은 input schema
string 하나에 SQL, URL, instruction을 모두 넣게 하지 않는다. enum, range, required field와 identifier format을 명시한다.
Structured output
machine-readable field와 user-facing text를 분리한다. model이 text를 다시 parsing하게 만들면 불필요한 확률적 단계를 추가한다.
Error taxonomy
retry 가능한 timeout, invalid argument, permission denied, not found, conflict를 구분한다. 모든 실패를 같은 text message로 반환하면 policy가 올바르게 분기하기 어렵다.
Idempotency와 confirmation
write action에는 idempotency key, dry-run 또는 preview, confirmation boundary를 설계한다. protocol 연결이 가능하다는 사실과 실행 권한은 다르다.
Tool output은 untrusted input이다
retrieved web page, database text, issue description이 model에게 instruction처럼 보일 수 있다. tool output은 data이며 상위 system policy를 바꾸는 명령이 아니다.
사용자 목표
→ host policy와 authorization
→ model tool proposal
→ schema validation
→ 사용자 confirmation가 필요한지 판단
→ server execution
→ output validation과 sanitization
→ model context에 최소 범위 전달
model probability가 높아도 policy check를 우회하지 않는다.
RAG, function calling, agent, MCP를 구분한다
| 개념 | 중심 질문 |
|---|---|
| RAG | 어떤 외부 근거를 찾아 context에 넣는가 |
| Function calling | model output을 어떤 structured call로 표현하는가 |
| Agent | 여러 관찰과 action을 어떤 loop와 policy로 조정하는가 |
| MCP | application과 capability provider가 어떤 protocol로 상호운용하는가 |
한 system이 네 가지를 모두 쓸 수 있지만 서로 대체 관계가 아니다.
예를 들어 MCP tool search_docs가 vector retrieval을 실행하고 agent가 결과를 보고 다시 query를 바꿀 수 있다. 여기서 RAG 수학은 search_docs 내부와 evidence 평가에, MCP는 discovery·call·result contract에, agent policy는 반복 여부에 관여한다.
End-to-end agent 성공을 계층별로 본다
간단한 chain은
로 분해할 수 있다.
관측 예시가 다음과 같다고 하자.
- tool 선택 0.95
- argument semantic correctness 0.9
- authorization 통과 0.98
- tool 성공 0.97
- 결과 사용 성공 0.9
그러면 단순 chain estimate는
약 73.1%다. final task score만 보면 어느 10%를 먼저 고쳐야 하는지 알기 어렵다.
무엇을 model에 맡기고 무엇을 code에 둘까
Model이 잘하는 쪽
- 자연어 intent 분류
- 불완전한 query reformulation
- unstructured result 요약
- 여러 evidence의 language synthesis
Deterministic code에 둘 쪽
- authorization
- amount와 date validation
- idempotency
- transaction boundary
- exact arithmetic
- schema validation
- destructive action confirmation
- audit log
확률 model의 유연성과 protocol·업무 규칙의 결정성을 섞지 않는다.
최신 명세를 읽는 방법
MCP는 versioned protocol이다. blog 글보다 다음 순서로 확인한다.
https://modelcontextprotocol.io/specification/latest가 가리키는 revision- base protocol과 lifecycle
- architecture와 capability negotiation
- 사용할 primitive 또는 client feature 문서
- TypeScript schema source of truth
- revision changelog와 security guidance
- SDK가 지원하는 protocol version
이 글이 확인한 latest는 2025-11-25다. 이후 revision이 나오면 version-dependent 문장은 최신 명세와 대조해야 한다.
연재 전체에서 논문으로 넘어가는 순서
Transformer 논문
- tensor shape
- scaled dot-product attention
- softmax와 mask
- residual과 normalization
- training objective와 complexity 표
Embedding·RAG 논문
- score function
- positive·negative sampling
- loss denominator
- candidate generation path
- metric cutoff와 dataset split
Fine-tuning·alignment 논문
- 어떤 parameter를 freeze하는가
- per-token log probability reduction
- reference model과 KL 방향
- preference data 생성 방식
- online rollout이 필요한가
Agent·MCP 문서
- model policy와 protocol state를 분리한다.
- capability discovery와 authorization을 구분한다.
- success를 selection, validation, execution, result use로 나눈다.
- write action의 confirmation과 idempotency를 확인한다.
- versioned schema를 source of truth로 본다.
마지막 체크리스트
- pretraining, continued pretraining, SFT의 data와 loss를 구분한다.
- token mean과 sequence mean loss 차이를 설명한다.
- full fine-tuning과 PEFT의 training memory와 inference compute를 구분한다.
- LoRA rank, target module, scaling과 merge를 설명한다.
- reward model의 pairwise probability를 계산한다.
- RLHF objective의 reward와 KL tradeoff를 설명한다.
- DPO 식에서 chosen과 rejected의 reference 대비 log-ratio를 읽는다.
- tool selection, argument validation, authorization, execution 성공을 분리한다.
- multi-step success와 retry의 조건부 probability를 계산한다.
- RAG, function calling, agent, MCP를 구분한다.
- MCP host, client, server의 책임을 설명한다.
- request, response, error, notification을 구분한다.
- initialization과 capability negotiation 순서를 설명한다.
- schema validation이 authorization을 대신하지 못함을 설명한다.
이제 전체 지도의 완료 체크리스트로 돌아가 빈 항목을 찾는다. 모르는 식이 나오면 과목 전체를 다시 시작하지 않고, 그 식의 값·shape·의미·비용부터 분해한다.
Reference
- Long Ouyang 외. Training language models to follow instructions with human feedback, 2022.
- Edward J. Hu 외. LoRA, 2021.
- Tim Dettmers 외. QLoRA, 2023.
- Rafael Rafailov 외. Direct Preference Optimization, 2023.
- Shunyu Yao 외. ReAct, 2022.
- Model Context Protocol. Architecture, revision 2025-11-25.
- Model Context Protocol. Base Protocol, revision 2025-11-25.
- Model Context Protocol. Lifecycle, revision 2025-11-25.
- Model Context Protocol. Server Features, revision 2025-11-25.
댓글