Dayward AI

Interview Bank

328 questions total; 6 shown with current filters.

Tag
235 more tags
#streaming5#structured-output5#chunking4#deployment4#distributed-systems4#rag4#system-prompt4#tool-calling4#client3#embeddings3#failure-modes3#ingestion3#mcp3#message-bus3#operations3#progressive-disclosure3#ranking3#timeline3#agent-loop2#agentic-rag2#agents-sdk2#caching2#citations2#code-review2#communication2#concurrency2#consistency2#context2#context-engineering2#context-rot2#cost-control2#data-modeling2#grounding2#hybrid-search2#langgraph2#latency2#model-migration2#model-routing2#multi-agent2#ordering2#pipeline-design2#prompt-basics2#prompt-engineering2#protocol2#rate-limiting2#react2#redis-streams2#responses-api2#retrieval2#retrieval-quality2#routing2#runtime2#sse2#state-management2#statelessness2#subagents2#system-design2#tool-design2#tooling2#tracing2#trade-offs2#transport2#vector-database2#versioning2#workflow2#abstention1#access-control1#agent-design1#agent-quality1#altitude1#approvals1#async1#async-task1#atomicity1#attention-budget1#auth1#av-sync1#behavioral1#bm251#candidate-selection1#capacity-planning1#chain-of-thought1#checkpointing1#ci1#citation-verification1#claude-code1#cli-design1#cloud1#compaction1#compression1#content-hash1#context-compression1#context-window1#contextual-retrieval1#cost-optimization1#cross-model1#dag1#data-quality1#database1#decision-making1#decomposition1#degradation1#deliberate-practice1#design1#diagnostics1#dimensions1#distribution1#docker1#documentation1#engineering-judgement1#engineering-tradeoffs1#eval1#event-driven1#fallback1#fan-out1#ffmpeg1#forking1#four-elements1#framework-design1#framework-selection1#golden-set1#hallucination1#handoffs1#headless1#hnsw1#hybrid1#hyde1#image-generation1#incremental-recompute1#incremental-sync1#index-maintenance1#index-routing1#indexing1#information-retrieval1#instruction-hierarchy1#intent-routing1#interrupt-merge1#interview-prep1#invalidation1#isolation1#ivfflat1#just-in-time1#knowledge-organization1#lease1#llm-as-judge1#llm-output-quality1#long-context1#loop-guard1#media-pipeline1#metadata1#metrics1#mobile1#model-selection1#multi-tenancy1#multimodal1#nodejs1#orchestration1#pagination1#parent-child1#pdf-parsing1#performance1#permissions1#persistence1#pgvector1#pipeline-reliability1#portfolio1#prioritization1#production-readiness1#prompt-assembly1#prompt-caching1#prompt-injection1#prompt-limits1#prompt-techniques1#prompt-template1#prompt-versioning1#provider-abstraction1#quality-check1#quantization1#query-transformation1#quiet-hours1#rank-fusion1#reasoning1#recall1#redis1#reflection1#refusal1#reporting1#reproducibility1#rerank1#retrieval-failure1#retrieval-metrics1#retry1#retry-semantics1#retry-strategy1#review1#rollback1#rrf1#sandbox1#sandboxing1#scalability1#scheduling1#schema-design1#scoping1#scripts1#secrets-management1#self-assessment1#self-presentation1#self-reflection1#service-architecture1#session-management1#sessions1#sharding1#skill-authoring1#skill-description1#skills1#spec1#state-machine1#stateless1#stopping-criteria1#subtitles1#task-graph1#team-governance1#testing1#tool-budget1#tool-execution1#tool-naming1#tools1#tts1#tuning1#ux1#validation1#vector-index1#verification1#workflow-engine1#xml-tags1

From Frontend Engineer to Agent Engineer in 30 Days

D7 Packaging It as a Service: Fastify + SSE + Docker (dg P07); Week One Retrospective

  • When turning a local agent script into a production service, what does the interface layer have to get right?把一个本地跑的 Agent 脚本改造成生产服务,接口层要重点考虑哪些事?
    Common in ChinaCommon overseasIntermediate#api-design#service-architecture#streaming

    How to reason about it · think before answering

    1. This tests whether you can name the assumptions hidden in a script. A generic checklist (auth, logging, monitoring) scores nothing; name the assumptions that silently break.
    2. List them first: one user (so history can live in a module-level variable), serial execution (no two requests mutating the same state), trusted input (you typed the arguments yourself), and a process whose life equals the session's. All four break in a service, and the first is hardest to catch because single-user local testing looks perfect.
    3. Then give the four decisions: response shape (single JSON versus streamed events), session identity (client-supplied id versus server cookie, and where history is stored), authentication and rate limiting (who may call, how often, and the per-call token ceiling), and how errors are expressed.
    4. Expand the last one — it is where this question is actually won. Once a streaming endpoint has written 200 and the first byte, the status code is already on the wire, so a later timeout, out-of-credit or upstream 500 can only surface as an agreed error event inside the stream. Validate everything you can before the first byte, because that is your last chance to speak in status codes.
    5. Add a production note: ship a health endpoint. Without one, orchestrators and load balancers cannot tell whether an instance is ready, and rolling deploys send traffic to a process that has not finished booting.
    6. Expect the follow-up: why cap tokens per request at the interface layer? Because agent cost is triggered by the caller and paid by you — no cap means handing your wallet to the client. Rate limiting is about money per call, not just QPS.

    分析过程 · 先想清楚再作答

    1. 这题考的是「你知不知道脚本里有哪些隐含假设」。答成一份笼统的清单(鉴权、日志、监控)拿不到分,要说出脚本时代默认成立、服务里立刻不成立的那几条。
    2. 先把假设列出来,这是最能体现工程视角的一步:只有一个用户(历史可以放模块级变量)、串行执行(不会有两个请求同时改一份状态)、输入可信(参数是自己敲的)、进程和会话同生共死(Ctrl+C 之后不用交代)。四条在服务里全部不成立,而第一条最难查,因为它在本地单人测试时表现完美。
    3. 然后给出四个必须做的决定:接口形状(一次性 JSON 还是流式推送)、会话标识(客户端带 sessionId 还是服务端发 cookie,以及历史存哪里)、鉴权与限流(谁能调、多久能调一次、单次 token 上限)、错误怎么表达。
    4. 第四条要单独展开,它是这题真正的区分点:流式接口一旦写出 200 和第一个字节,状态码就已经发出去了,之后模型超时、余额不足、上游 500,都只能在流里补发一个约定好的 error 事件。所以推流之前必须把能校验的全部校验完,那是你最后一次能用状态码好好说话的机会。
    5. 再补一条生产视角:服务要有健康检查接口。没有它,编排系统和负载均衡就没法判断这个实例能不能接流量,滚动发布时会把请求打给一个还没起好的进程。
    6. 可以预期的追问:单次请求的 token 上限为什么要在接口层限制?因为 Agent 的成本是请求方触发、你来买单,不设上限就等于把钱包交给调用方——限流限的不只是 QPS,还有每次调用能烧多少钱。

    Key points

    • A script's four assumptions all break in a service: single user, serial execution, trusted input, and a process that dies with the session
    • Session state must be keyed by session id, and in-process storage means data is lost on restart and blocks horizontal scaling
    • Four interface decisions: response shape, session identity, auth and rate limiting including a per-call token ceiling, and error semantics
    • A streaming endpoint cannot report errors by status code after the first byte, so define an in-stream error event and move all validation ahead of it
    • Expose a health endpoint, or orchestrators cannot tell whether the instance is ready for traffic

    答题要点

    • 脚本的四个隐含假设在服务里全部不成立:单用户、串行、输入可信、进程与会话同生共死
    • 会话状态必须按 sessionId 隔离,且要意识到放进程内存意味着重启即丢、无法水平扩容
    • 四个接口决定:响应形状、会话标识、鉴权与限流(含单次 token 上限)、错误表达方式
    • 流式接口推流之后无法用状态码报错,必须约定一个流内的 error 事件,并把校验全部前置到第一个字节之前
    • 提供健康检查接口,否则编排系统无法判断实例能不能接流量

D19 Cross-Service Agent Integration: Minting a User-Level JWT, JWKS Signature Verification, the inject/memory/usage Interfaces, Idempotent externalId

  • For service-to-service calls, would you use a service token or a user token? When does each apply?两个服务之间调用,你会用服务级令牌还是用户级令牌?分别适用于什么场景?
    Common in ChinaCommon overseasIntermediate#auth#security#api-design

    How to reason about it · think before answering

    1. The hinge is each. Answering user tokens are safer turns a design question into a slogan — the interviewer wants the conditions under which each one is correct, and the concrete cost of choosing wrong.
    2. Give the deciding question first: is there a specific user behind this call? If yes, it must be a user token. If not — fetching config, reporting metrics, running a reconciliation batch — a service token is the right answer, and stuffing in a user id would fabricate audit history.
    3. Then state the three reasons as costs, not virtues. A leaked service token means every user's data at once; a leaked user token means one user, and it expires in fifteen minutes. Audit logs with a service token only show that some service called, never on whose behalf. And a downstream service doing per-user authorization is forced to trust a userId in the request body, which the caller writes freely.
    4. Add the production view: it is rarely either-or. Real systems use the service credential to obtain user tokens — the caller proves who it is once, then mints a short-lived token representing one user. The service credential then appears only at the minting step, never on every business call.
    5. Expect: what if a token leaks? Answer in two layers — a short lifetime (fifteen minutes here) does most of the containment, and a jti denylist is the supplement. Do not lead with a denylist: it puts a database lookup in front of every verification and gives away the whole point of stateless verification.
    6. Expect: how fine-grained should scopes be? Offer a usable rule — split along asymmetric risk. A bad read leaks information; a bad write poisons data that keeps influencing every later turn. So read and write always split; finer than that only if a real caller genuinely needs just one half.

    分析过程 · 先想清楚再作答

    1. 题眼在「分别」。答「用户级更安全」就把一道设计题做成了口号题——面试官想看你能不能说出两者各自成立的条件,以及选错的具体代价。
    2. 先给判断依据,一句话就能拆开:这次调用**有没有一个具体的用户在背后**。有,就必须是用户级;没有(拉配置、上报指标、跑对账批处理),服务级才是对的,硬塞一个用户 id 进去反而是伪造审计记录。
    3. 然后把用户级的三条理由说成代价而不是优点:服务级令牌泄露一次等于全量用户数据泄露,用户级泄露一张只丢一个用户且十五分钟自动作废;服务级在审计日志里只能查到「某服务调了一次」,查不到替谁操作;下游做用户级权限判断时,服务级令牌逼着它去信请求体里的 userId,而那是调用方可以随便写的。
    4. 补一句生产视角:两者不是二选一,真实系统里常常是「服务级令牌用来换用户级令牌」——调用方先用自己的服务凭证证明自己是谁,再申请一张代表某个用户的短期令牌。这样服务凭证只出现在铸造这一步,不出现在每一次业务调用里。
    5. 可以预期的追问一:令牌泄露了怎么办?答案要分两层——短有效期(本课 15 分钟)是止损的主力,撤销列表按 jti 拉黑是补充;不要上来就说「用黑名单」,那等于给每次验签加一次数据库查询,把无状态验签的好处全赔进去了。
    6. 可以预期的追问二:那 scope 该切多细?给一条可操作的判据——按「读写不对称的风险」切,读错了泄露信息、写错了污染数据且会持续影响后续每一轮对话,所以 read 和 write 必须分开;再细就要看有没有真实的调用方只需要其中一半。

    Key points

    • The deciding question is whether a specific user stands behind the call: yes means user token, no (config, metrics, reconciliation) means service token
    • A leaked service token exposes every user; a leaked user token exposes one and expires on its own
    • Auditing has to reach a person — only the sub claim answers who the call was made on behalf of
    • With a service token the downstream must trust a userId in the request body, which the caller can forge
    • Common production shape: the service credential only buys short-lived per-user tokens and never appears on business calls
    • After a leak, short lifetimes do the containment and a jti denylist supplements it — do not trade away stateless verification by default

    答题要点

    • 判断依据是「这次调用背后有没有一个具体用户」:有就用用户级,没有(配置、指标、对账批处理)才用服务级
    • 服务级令牌泄露的爆炸半径是全量用户,用户级只影响一个用户且短期自动失效
    • 审计要能落到人:只有 sub 字段能回答「当时是替谁操作的」
    • 下游要做用户级权限判断时,服务级令牌逼着它去信请求体里的 userId,而那是调用方可以伪造的
    • 生产里常见组合:服务凭证只用来换取代表某个用户的短期令牌,不出现在每次业务调用里
    • 泄露后的止损顺序是短有效期优先、jti 撤销列表补充,别一上来就上黑名单换掉无状态验签
  • How do you design an idempotency key for cross-service calls — who generates it, where does it live, and what do you return on a repeat?跨服务调用的幂等键该怎么设计?由谁生成、存在哪、重复了返回什么?
    Common in ChinaCommon overseasIntermediate#idempotency#distributed-systems#api-design

    How to reason about it · think before answering

    1. This question separates people entirely on implementation detail. Anyone can define idempotency; answering who generates the key, where it lives, and what a repeat returns shows whether you have actually built one.
    2. Start with the rule: the final arbiter must be a database uniqueness constraint, not an application-level check-then-insert. Check-then-insert always passes single-process tests and produces duplicates the moment you run two replicas — both check, both find nothing, both insert. The window is too narrow to reproduce under load testing and wide enough to produce dirty rows daily in production.
    3. Who generates it: the caller, because only the caller knows that two retries are the same event. But the key must be derived from the event itself, never a fresh random UUID per retry — that is idempotency in name only. Same criterion as the user-message case from day 8.
    4. Cross-service adds one trap worth the most points: never use the caller's raw id as the key. Two different callers will eventually both produce evt-1, and the failure is not an error — the second user silently receives nothing, because their event is treated as a duplicate and the logs look clean. Namespace it: issuer plus user id plus event id, all three taken from the verified token so none of them can be forged.
    5. What to return also matters: a repeat gets 200 with the original result, not 409. Repeats are normal in distributed systems; a 409 makes the caller's retry logic treat it as a failure and the situation compounds.
    6. Expect: does this table grow forever? Yes, so give it a retention window — a TTL matching the replay window the business tolerates, say seven days, with periodic cleanup. Say plainly that a duplicate arriving after cleanup is treated as new; that is a stated trade-off, not a hole.

    分析过程 · 先想清楚再作答

    1. 这题的区分度全在实现细节上。概念谁都会说,能不能答对「谁生成、存在哪、返回什么」这三个具体问题,直接暴露你有没有真做过。
    2. 先立一条铁律:**幂等的最终裁判必须是数据库的唯一约束**,不是应用层的「先查一下有没有」。先查后插在单进程测试里永远是对的,一上多实例就出双份——两个副本同时查、同时发现没有、同时插入,这个时间窗压测时窄到复现不出来,上线后每天出几条脏数据。
    3. 再答「谁生成」:由**调用方**生成,因为只有它知道重试的那两次是同一件事;但键必须由事件内容决定,不能是每次重试重新生成的随机 UUID——那等于没有幂等。这条和 D8 的用户消息幂等是同一条判据。
    4. 跨服务比同服务多一个坑,这是本题最有价值的一点:**调用方给的 id 不能直接当键用**。两个不同的调用方各自造出 evt-1 是迟早的事,撞车之后的表现不是报错,而是后来那个用户静默收不到消息——他的事件被当成重复丢掉了,日志里干干净净。所以落库前要加命名空间,用「签发方 + 用户 id + 事件 id」三段拼,而且三段都取自验签后的令牌,伪造不了。
    5. 「返回什么」也是个坑:重复送达要返回 200 并附上第一次的结果,不要返回 409。重复不是错误,是分布式系统的常态;回 409 会让调用方的重试逻辑把它当失败处理,越重试越乱。
    6. 可以预期的追问:这张表会不会无限涨?答「会,所以要有保留期」——按业务能接受的重放窗口设一个 TTL(比如 7 天)定期清理,同时说明清理之后超期的重复请求会被当成新事件,这是一个明确的、可接受的取舍,不是漏洞。

    Key points

    • The arbiter is a unique constraint plus on conflict do nothing; check-then-insert duplicates as soon as you run two replicas
    • The caller generates the key, but it must be derived from the event — a fresh UUID per retry is not idempotency
    • Never use the caller's raw id: namespace it with issuer plus user id plus event id, all taken from the verified token
    • A collision does not raise an error; it silently drops another user's event and leaves clean logs
    • Return 200 with the original result on a repeat, never 409, or the caller's retry logic treats success as failure
    • Give the table a retention window and state that post-cleanup repeats count as new events — a stated trade-off, not a hole

    答题要点

    • 最终裁判是数据库唯一约束加 on conflict do nothing,先查后插在多实例下必然出双份
    • 键由调用方生成,但必须由事件内容决定,随机 UUID 等于没有幂等
    • 调用方给的 id 不能直接当键:加命名空间(签发方 + 用户 id + 事件 id),三段都取自验签后的令牌
    • 撞车的后果不是报错而是另一个用户静默收不到消息,日志里看不出异常
    • 重复送达返回 200 加第一次的结果,不要返回 409,否则调用方会当失败继续重试
    • 幂等表要设保留期,超期后的重复会被当成新事件,这是明确取舍不是漏洞

D20 Scheduled Jobs and Proactive Outreach: Time Zones, Quiet Hours, Daily Caps, a Notification Provider Abstraction

  • You have abstracted model calls, payments and notification channels behind providers. How does the notification interface differ from the other two?模型调用、支付、通知渠道你都做过 provider 抽象。通知这一份接口和另外两份有什么不同?
    Common in ChinaCommon overseasIntermediate#provider-abstraction#api-design#retry-semantics

    How to reason about it · think before answering

    1. This question separates applying a pattern from understanding one. Saying all three are the same — an interface with several implementations so you can swap vendors without touching business code — only covers the shared part; the interviewer wants to see whether you spotted the differences and encoded them in the interface.
    2. Acknowledge the commonality in one line: each pushes a replaceable dependency behind an interface, business code depends only on the interface, and the selection point lives in exactly one place. Correct, but not differentiating.
    3. Then give three differences, which is where the points are. First, accepted is not delivered: when a payment gateway returns success the money has moved, but when a notification channel returns success it has merely taken the message, and actual delivery arrives later as an asynchronous receipt. So the result is accepted, never delivered, and it must carry the provider-side message id so the receipt can be correlated.
    4. Second, throttling lives at a different layer: the channel has its own per-second ceiling and tells you to come back later with a 429 plus a retry interval — a channel-level technical constraint — while the daily cap is a user-level courtesy constraint. Collapsing them into one concept makes them impossible to tune separately: one says this line is congested, the other says this person has been interrupted enough today.
    5. Third, there is no undo: payments have refunds, notifications do not. Once handed to the channel the message is gone, and cancel only means anything before that handoff. So the interface must not expose a cancel method — leaving an operation that cannot work is worse than not having it, because callers will actually use it.
    6. Expect: how do you design retries then? Three classes. Throttling backs off for the interval the channel gave you. Parameter errors (invalid body, unsubscribed user) are not retryable, so give up and return the daily slot. Server errors and timeouts are retryable but must carry the same idempotency key — you can delete a duplicate row, you cannot un-buzz a phone. Add a test for the abstraction itself: if a new channel only has to implement send the message, the boundary is right; if it also needs to know whether it is quiet hours or which message of the day this is, business rules have leaked into the channel layer.

    分析过程 · 先想清楚再作答

    1. 这题在考你是「会套模式」还是「懂模式」。把三者说成一回事——都是接口加多个实现、换厂商不改业务——只答到了共性那一层,面试官真正想看的是你有没有识别出差异并把它写进接口。
    2. 先给共性,一句话带过:都是把「会被替换的东西」推到接口后面,业务代码只认接口,选择点集中在一处。这一层是对的,但不构成区分度。
    3. 然后给三条差异,这是拿分点。第一,收下不等于送达:支付网关返回成功钱就划走了,通知渠道返回成功只表示它收下了,真正送达是过一会儿通过回执异步告诉你的。所以返回值只能叫 accepted 不能叫 delivered,而且必须带渠道侧的消息标识,回执回来时靠它对上号。
    4. 第二,限流的层次不同:渠道自带每秒条数上限并会用 429 加重试间隔告诉你稍后再来,这是**渠道维度的技术约束**;而每日发送上限是**用户维度的礼貌约束**。两者混成一个概念就没法分别调整——一个说的是这条线路挤不下了,一个说的是这个人今天已经被打扰够了。
    5. 第三,没有撤销:支付有退款,通知发出去就撤不回来,取消只在交给渠道之前有效。所以接口里不能出现 cancel——在接口上留一个做不到的操作比根本没有这个操作更危险,调用方会真的去用它。
    6. 可以预期的追问:那失败重试怎么设计?答分三类:限流按渠道给的时长退避重试;参数错(正文非法、用户已退订)不可重试,直接放弃并把当天的名额还回去;服务端错误或超时可重试但必须带同一个幂等键——数据库里多一行你能删掉,用户手机上多响一声删不掉。再补一条判断抽象好坏的判据:新接一个渠道时如果它只需要实现「把这条消息发出去」,抽象就对了;如果它还得知道现在是不是安静时段、这是今天第几条,说明业务规则泄进了渠道层。

    Key points

    • The shared part is pushing a replaceable dependency behind an interface with a single selection point — that is only the baseline
    • Accepted is not delivered: name the result accepted and carry a provider message id so async receipts can be correlated
    • Throttling has two layers: the channel's per-second ceiling is technical, the daily cap is a user-level courtesy rule, and they must stay separate
    • Notifications have no undo, so the interface must not expose cancel — an unimplementable operation is worse than none
    • Three retry classes: back off for the channel's interval on throttling, give up and release the slot on parameter errors, retry server errors with the same idempotency key
    • Test the boundary: a new channel should only implement send; needing to know quiet hours or today's count means business rules leaked into the channel

    答题要点

    • 共性是把可替换依赖推到接口后面、选择点集中一处,但这只是及格线
    • 收下不等于送达:返回值叫 accepted 不叫 delivered,必须带渠道侧消息标识以便异步回执对号
    • 限流分两层:渠道的每秒上限是技术约束,每日发送上限是用户维度的礼貌约束,不能合并
    • 通知没有撤销,接口里不能有 cancel;留一个做不到的操作比没有更危险
    • 重试分三类:限流按渠道给的时长退避、参数错不可重试并归还名额、服务端错误可重试但必须带同一个幂等键
    • 判断抽象切没切对:新渠道只需实现发送就对了,还要知道安静时段和当天条数就说明业务泄进了渠道层

MCP in 7 Days: Wire Tools Into Any Agent

D3 Resources and Prompts: URI Templates, Change Notifications, Progress and Logging, Pagination, and Client Capabilities

  • Why must MCP pagination cursors be opaque, and what breaks if a client parses them?MCP 的分页游标为什么必须是不透明的?如果客户端去解析它,会出什么问题?
    Common in ChinaCommon overseasIntermediate#pagination#api-design

    How to reason about it · think before answering

    1. It looks like a spec-recitation question but really tests whether you have shipped a paginated public API. Quoting the rule earns nothing; naming the concrete failure does.
    2. Start from what a cursor holds. A server may encode an offset, a primary key, a timestamp, or encrypted state, and it may change that at any time. A client that parses one format breaks everywhere the day the server switches, because parsing turned an internal detail into a public contract.
    3. Second failure is forgery. A client that fabricates offset:9999 bypasses the server's control over paging range, and if the cursor encodes filters or permissions, forging it is a privilege escalation.
    4. Third and nastiest: treating an empty string as the end. The spec is explicit that only a missing nextCursor ends the sequence; an empty string is a valid cursor. Getting this wrong silently drops the last page with no error, which tests rarely catch.
    5. Conclusion: a client may make exactly one judgment about a cursor — whether nextCursor is present. Page size likewise must not be assumed fixed. Servers should reject invalid cursors with -32602 rather than silently returning page one, which would loop the client forever.
    6. Likely follow-up: what bites the server side? Offset cursors require a stable ordering, since an insertion shifts everything after it, so either sort first or encode the last item's key instead.

    分析过程 · 先想清楚再作答

    1. 这题表面考规范条文,实际考「有没有做过带分页的对外接口」。只背出「规范说不透明」拿不到分,要能说出解析之后具体哪一步会崩。
    2. 拆法:先问游标里到底装的是什么。服务端可以装偏移量、主键、时间戳、甚至一段加密状态,而且**换实现时它随时会变**。客户端一旦按某种格式解析,服务端从偏移量换成主键那天,所有客户端一起挂——这是把服务端的内部实现变成了公开契约。
    3. 第二个坑是伪造。客户端自己造一个 offset:9999 递给服务端,等于绕过了服务端对翻页范围的控制;如果游标里编了权限或过滤条件,伪造它就是一次越权。
    4. 第三个坑最阴:把空字符串当成结束。规范写死了只有 nextCursor **缺失**才代表没有下一页,空串是完全合法的游标。判错的表现是最后一页数据被静默丢掉,而且不报错,测试也很难发现。
    5. 结论:客户端对游标只允许做一个判断——nextCursor 在不在。页大小同理不得假设固定值,服务端随时可以改。非法游标服务端应当回 -32602,而不是静默返回第一页,否则客户端会陷进死循环。
    6. 可预期的追问:那服务端这边有什么坑?偏移量式游标要求列表顺序稳定,中途插入一条会让后面全部错位,所以要么先排序、要么把游标编成上一条的主键。

    Key points

    • Cursor contents are server internals; parsing them turns an implementation detail into a public contract that breaks on any change
    • Forged cursors bypass server-side paging control, and become privilege escalation if the cursor encodes filters or permissions
    • Only a missing nextCursor ends the sequence — an empty string is valid, and getting it wrong silently drops the last page
    • Page size is server-decided and must not be assumed fixed; invalid cursors should return -32602 rather than silently resetting

    答题要点

    • 游标内容是服务端的内部实现,解析它等于把实现细节变成公开契约,服务端换实现时客户端全挂
    • 伪造游标可以绕过服务端对翻页范围的控制,游标里若编了过滤或权限条件就是越权
    • 只有 nextCursor 缺失才代表结束,空字符串是合法游标,判错会静默丢掉最后一页
    • 页大小由服务端决定不得假设固定,非法游标服务端应回 -32602 而不是静默回第一页

D4 Remote MCP: the Streamable HTTP Binding, the Stateless Model and Request Metadata, OAuth 2.1 Authorization, Container Deployment

  • The 2026-07-28 revision removed protocol-level sessions. How should a remote server that needs cross-call state — a shopping cart, a database transaction — be designed?2026-07-28 去掉了协议级会话。那一个需要跨调用保存状态的远程服务端——比如购物车、数据库事务——应该怎么设计?
    Common in ChinaCommon overseasIntermediate#statelessness#api-design

    How to reason about it · think before answering

    1. The screen is whether you treat statelessness as a design constraint. Answering 'use Mcp-Session-Id' fails immediately — that header was removed. So does 'keep it in server memory keyed by connection', since clients are not required to reuse connections.
    2. Give the structure first: state must travel with the client, and the server trusts only what arrives in the request. Two concrete shapes — a server-minted explicit handle returned by a creation tool and passed back as an ordinary tool argument, or a signed opaque blob like the requestState used by multi round-trip requests.
    3. The difference is who stores the data. A handle is just a primary key into server-side storage; a requestState encodes the context itself, so the server stores nothing. Handles suit long-lived business objects, requestState suits continuing a single interaction.
    4. Conclusion: either way the server keeps nothing per client in memory, so any replica can serve any request and scaling needs no sticky routing — which is exactly what the change was buying.
    5. Volunteer the security half: a handle is a name, not a credential. Generate it from a secure random source, bind it server-side to the authenticated principal (key storage as user id plus handle), expire it, and re-authorize on every call — the spec says possession of a handle must not be treated as authentication. requestState passes through the client, so it is attacker-controlled input and must be integrity-protected with HMAC or AEAD, carrying the principal, an originating-request identifier, and a short expiry.
    6. Likely follow-up: what about requestState across replicas? Share the signing key; it is still stateless because the state lives with the client and replicas only verify. A second follow-up is single use — signing bounds the replay window but does not guarantee one-time consumption, which needs a server-side redemption record.

    分析过程 · 先想清楚再作答

    1. 这题在筛「有没有把无状态当成设计约束」。答「用 Mcp-Session-Id 头」的当场出局,那个头这一版已经删了;答「存在服务端内存里按连接查」的同样出局,因为客户端根本不保证复用连接。
    2. 先给结构:状态必须由客户端携带,服务端只认请求里带来的东西。落地成两种形态——一是服务端铸造的显式句柄,创建工具返回一个 id,后续调用把它当普通工具参数传回来;二是签过名的不透明状态串,比如多轮请求里的 requestState,服务端把上下文签进去,重试时原样收回。
    3. 两者的差别在于「谁存数据」:句柄背后的购物车内容还是存在服务端的库里,句柄只是主键;requestState 是把上下文本身编码进字符串,服务端零存储。前者适合长期存在的业务对象,后者适合一次交互内的续接。
    4. 结论:不管哪种,服务端内存里都不为某个客户端留东西,所以任何副本都能处理任何请求,扩容不需要粘性路由——这正是这次改动想换来的东西。
    5. 安全是必须主动补的一句:句柄是名字不是凭证。要用安全随机数生成、绑定到已认证的主体(按 user_id 加 handle 做键)、设过期时间,并且每次调用重新校验调用者身份。规范明确写了服务端不得把持有句柄当成身份认证。requestState 同理,它经客户端转手,是攻击者可控输入,必须 HMAC 或 AEAD 验签,并把主体、原请求标识、短过期签进去。
    6. 可预期的追问:多副本时 requestState 怎么办?答案是所有副本共享签名密钥即可,这仍然是无状态的——状态在客户端手里,副本只负责验签。追问二可能是「怎么保证一次性」,答案是签名只能缩小重放窗口,真要单次消费得自己在服务端加一层消费记录。

    Key points

    • State travels with the client: the server mints an explicit handle that later calls pass back as an ordinary tool argument
    • Within one interaction, a signed opaque blob works with zero server storage; replicas just share the signing key
    • A handle is not a credential: securely random, bound to the authenticated principal, expiring, re-authorized on every call
    • The payoff is that any replica serves any request, so scaling needs no sticky routing and retries are cheap

    答题要点

    • 状态必须由客户端携带:服务端铸造显式句柄,作为普通工具参数在后续调用里传回
    • 一次交互内的续接可以用签名的不透明状态串,服务端零存储,多副本共享签名密钥即可
    • 句柄不是凭证:安全随机生成、绑定已认证主体、设过期,每次调用重新鉴权
    • 收益是任何副本能处理任何请求,扩容不需要粘性路由,重启后重发即可