Approval Phase B¶
Feature spec for cross-SDK implementation planning. Source: derived from apcore-mcp/docs/srs-apcore-mcp.md and approval-handler.md Created: 2026-06-12
Overview¶
Approval Phase B complements Phase A (ElicitationApprovalHandler) by providing a storage-backed approval flow that survives beyond the lifetime of a single MCP request. Instead of blocking synchronously for an inline user response via MCP elicitation, StorageBackedApprovalHandler persists the approval request to an ApprovalStore, returns an APPROVAL_PENDING sentinel immediately, and relies on an external system (Slack, email, web UI, webhook) to resolve the approval out of band. The agent polls via the __apcore_approval_check meta-tool and retries the original call once the approval is resolved.
Phase B is not a replacement for Phase A. Both implement the same ApprovalHandler protocol from the apcore SDK; the choice between them is a deployment decision.
When to Use Each Phase¶
| Criterion | Phase A: ElicitationApprovalHandler |
Phase B: StorageBackedApprovalHandler |
|---|---|---|
| Approval lifetime | Short-lived (seconds to minutes) | Long-lived (minutes to days) |
| MCP client support | Requires elicitation support in client | No elicitation required |
| Flow style | Synchronous, inline | Asynchronous, polling |
| Resolution path | User responds inside the MCP client UI | External system (Slack/email/web UI) |
| Persistence | None (in-memory per request) | Required (survives restarts) |
| Agent retry | Not required; handler blocks until resolved | Required; agent must poll and retry |
Choose Phase A when the MCP client (e.g., Claude Desktop) supports elicitation and the user is present at the keyboard. Choose Phase B for automated pipelines, mobile approvals, team workflows, or any case where the approver is not watching the terminal in real time.
Complete Flow¶
The numbered steps below trace a full approval cycle from initial call to approved retry.
1. Agent calls some_module(args)
→ apcore calls handler.request_approval(ApprovalRequest)
→ handler generates approval_id (UUID v4)
→ handler.save_pending(approval_id, module_id, args) → stored
→ handler fires notify_callback(approval_id, module_id, args) [fire-and-forget]
→ returns ApprovalResult(status="pending", approval_id="abc-123")
→ apcore raises ApprovalPendingError(approval_id="abc-123")
→ bridge returns: { errorType: "APPROVAL_PENDING", details: { approvalId: "abc-123" } }
2. Agent polls:
__apcore_approval_check({ "approval_id": "abc-123" })
→ { "approval_id": "abc-123", "status": "pending" }
3. External system resolves (out of band):
# Python
store.resolve("abc-123", approved=True)
# TypeScript
await store.resolve("abc-123", { approved: true })
# Rust
store.resolve("abc-123", true, None).await
4. Agent polls again:
__apcore_approval_check({ "approval_id": "abc-123" })
→ { "approval_id": "abc-123", "status": "approved" }
5. Agent retries:
some_module(args, _meta={ "approvalId": "abc-123" })
→ apcore calls handler.check_approval("abc-123")
→ store.get_result("abc-123") → { approved: true }
→ execution proceeds normally
Rejection path¶
If the external system rejects:
store.resolve("abc-123", approved=False, reason="Not authorized") # Python
await store.resolve("abc-123", { approved: false, reason: "Not authorized" }) # TypeScript
store.resolve("abc-123", false, Some("Not authorized")).await # Rust
On the next poll:
On retry with _meta.approvalId, the handler returns ApprovalResult(status="rejected") and apcore surfaces the rejection to the agent.
ApprovalStore Interface¶
ApprovalStore is the persistence abstraction implemented by all store backends. All three SDKs define an identical behavioral contract; method names use snake_case (Python/Rust) or camelCase (TypeScript).
save_pending(approval_id, module_id, arguments)¶
Persists a new pending approval record.
- approval_id — UUID v4 string; generated by
StorageBackedApprovalHandlerbefore this call. - module_id — String identifier of the module requiring approval.
- arguments — Dict/object of the arguments passed to the module. Stored for reference by the external approver system; NOT returned in
get_result()(see note below). - Idempotency — Must be idempotent per
approval_id. A second call with the sameapproval_idsilently no-ops or overwrites with identical data. This prevents duplicate records on network retries. - Initial status — Always
"pending".
get_result(approval_id) → Record | None¶
Retrieves the current state of an approval record.
- Returns
None(Python/Rust) ornull/undefined(TypeScript) for unknownapproval_idvalues. - Returns a record with at minimum:
{ "approval_id": str, "status": "pending" | "approved" | "rejected" }. reasonfield is included when present (set duringresolve()).argumentsare not included in the returned record. They are accepted insave_pending()for the notify callback and external UI display, then dropped afterresolve()to reclaim memory and avoid leaking sensitive inputs.
resolve(approval_id, approved, reason?) → bool¶
Resolves an approval record to a terminal state.
- approval_id — Must match a previously saved pending record.
- approved — Boolean.
True/true→"approved"status;False/false→"rejected"status. - reason — Optional string. Stored and returned in subsequent
get_result()calls. - Returns —
True/trueif the record was successfully resolved;False/falseif: - The
approval_idis unknown. - The record was already resolved (idempotency guard — prevents double-resolve races).
- Side effects — After resolve,
argumentsMAY be dropped by the implementation. TheInMemoryApprovalStoredrops them immediately. Persistent stores should document their own eviction policy.
Cross-language signatures¶
# Python (ApprovalStore ABC)
class ApprovalStore(ABC):
@abstractmethod
async def save_pending(self, approval_id: str, module_id: str, arguments: dict) -> None: ...
@abstractmethod
async def get_result(self, approval_id: str) -> dict | None: ...
@abstractmethod
async def resolve(self, approval_id: str, approved: bool, reason: str | None = None) -> bool: ...
// TypeScript
interface ApprovalStore {
savePending(approvalId: string, moduleId: string, arguments: Record<string, unknown>): Promise<void>;
getResult(approvalId: string): Promise<ApprovalRecord | null>;
resolve(approvalId: string, options: { approved: boolean; reason?: string }): Promise<boolean>;
}
// Rust
#[async_trait]
pub trait ApprovalStore: Send + Sync {
async fn save_pending(&self, approval_id: &str, module_id: &str, arguments: serde_json::Value) -> Result<()>;
async fn get_result(&self, approval_id: &str) -> Result<Option<ApprovalRecord>>;
async fn resolve(&self, approval_id: &str, approved: bool, reason: Option<String>) -> Result<bool>;
}
InMemoryApprovalStore¶
InMemoryApprovalStore is the reference implementation bundled with all three SDKs. It is provided for testing only and MUST NOT be used in production.
Why not production: All state is lost on process restart. In a multi-instance deployment, each instance holds a disjoint store — cross-instance polls will return None as if the approval never existed.
Memory management¶
Because long-lived approvals can accumulate without bound, InMemoryApprovalStore applies two defensive caps:
| Parameter | Default | Description |
|---|---|---|
ttl_seconds |
3600 (1 hour) |
Records older than this are eligible for sweep. |
max_records |
10000 |
Hard cap on total stored records. |
sweep_interval_seconds |
300 (5 min) |
How often the background sweep task runs (where applicable). |
- TTL sweep — Expired records are removed during periodic sweeps. Accessing a swept record via
get_result()returnsNone(same as unknown). - max_records cap — When the cap is reached,
save_pending()raisesApprovalStorageCapacityError(Python/TypeScript) or returns anErr(CapacityExceeded)(Rust). This is mapped through the Error Mapper before reaching the MCP client. - No persistence — Records vanish on GC, restart, or eviction. The store does not write to disk or any external service.
Instantiation¶
# Python — defaults
store = InMemoryApprovalStore()
# Python — custom limits
store = InMemoryApprovalStore(ttl_seconds=600, max_records=500)
// TypeScript
const store = new InMemoryApprovalStore();
const store = new InMemoryApprovalStore({ ttlSeconds: 600, maxRecords: 500 });
// Rust
let store = InMemoryApprovalStore::new();
let store = InMemoryApprovalStore::with_config(InMemoryStoreConfig {
ttl_seconds: 600,
max_records: 500,
..Default::default()
});
APCoreMCP Integration¶
APCoreMCP accepts approval_store (Python/Rust snake_case) / approvalStore (TypeScript camelCase) as a constructor parameter. When provided, the factory automatically wraps it in a StorageBackedApprovalHandler and registers __apcore_approval_check as a meta-tool alongside the __apcore_task_* tools.
# Python
mcp = APCoreMCP("./extensions",
approval_store=InMemoryApprovalStore(),
approval_notify=my_slack_notifier, # optional
)
// TypeScript
const mcp = new APCoreMCP(registry, {
approvalStore: new InMemoryApprovalStore(),
approvalNotify: mySlackNotifier, // optional
});
// Rust
let mcp = APCoreMCP::builder()
.backend(executor)
.approval_store(Arc::new(InMemoryApprovalStore::new()))
.approval_notify(my_slack_notifier) // optional
.build()?;
Parameter precedence¶
- Passing
approval_storeauto-creates aStorageBackedApprovalHandlerthat wraps the store. This is the standard path. - Passing
approval_handlerdirectly bypassesapproval_storeentirely and uses the provided handler as-is. Use this to supply a fully customApprovalHandlerimplementation (e.g., one backed by a message queue) without going throughStorageBackedApprovalHandler. - Passing both
approval_storeandapproval_handleris a configuration error and raisesValueError/ConfigurationErrorat construction time. - Passing neither leaves the approval handler as
None; modules that require approval will have theirApprovalPendingErrorsurface directly to the agent with no poll mechanism.
__apcore_approval_check Meta-Tool Spec¶
This tool is registered automatically whenever a StorageBackedApprovalHandler is active. It follows the same __apcore_ reserved-prefix convention as the async task meta-tools.
Tool name¶
__apcore_approval_check
Input schema¶
{
"type": "object",
"properties": {
"approval_id": {
"type": "string",
"description": "The approval_id returned in the APPROVAL_PENDING error details."
}
},
"required": ["approval_id"],
"additionalProperties": false
}
Output schema¶
{
"type": "object",
"properties": {
"approval_id": { "type": "string" },
"status": { "enum": ["pending", "approved", "rejected"] },
"reason": { "type": "string" }
},
"required": ["approval_id", "status"]
}
reason is only present when the record carries one (i.e., resolve() was called with a reason string).
is_error behaviour¶
- is_error: false in all non-exception outcomes, including when
approval_idis not found. Unknown IDs return{ "approval_id": "...", "status": "rejected" }rather than an error. This ensures agents can branch cleanly onstatuswithout needing separate error-path handling. - is_error: true only when
approval_idis missing or empty in the request. This is the only exception case; it indicates a malformed call rather than a normal "not found" result.
Example responses¶
// Pending
{ "approval_id": "abc-123", "status": "pending" }
// Approved
{ "approval_id": "abc-123", "status": "approved" }
// Rejected with reason
{ "approval_id": "abc-123", "status": "rejected", "reason": "Not authorized by policy" }
// Unknown id — not an error, surfaces as rejected
{ "approval_id": "abc-123", "status": "rejected" }
// Missing approval_id — is_error: true
{ "error": "INVALID_ARG", "message": "approval_id is required" }
notify_callback Contract¶
The approval_notify / approvalNotify parameter accepts an optional callback that is invoked once each time request_approval() stores a new pending record. Its purpose is to trigger an external notification (e.g., post a Slack message, send an email) so a human approver is alerted.
Invocation semantics¶
- Called once per
request_approval()call — not on poll, not on retry. - Called after
save_pending()succeeds. - Failures are logged at warning level and swallowed. The callback MUST NOT propagate exceptions to the module caller; the approval flow proceeds regardless of notification success or failure.
- The callback is fire-and-forget.
StorageBackedApprovalHandlerdoes not await its result (Python/TypeScript) or join its future (Rust) before returningApprovalResult(status="pending").
Signature¶
# Python — sync or async, both accepted
def notify(approval_id: str, module_id: str, arguments: dict) -> None: ...
async def notify(approval_id: str, module_id: str, arguments: dict) -> None: ...
// TypeScript
type ApprovalNotifyCallback = (
approvalId: string,
moduleId: string,
arguments: Record<string, unknown>,
) => void | Promise<void>;
// Rust — synchronous callback wrapped in Arc
pub type ApprovalNotifyCallback =
Arc<dyn Fn(String, String, serde_json::Value) + Send + Sync + 'static>;
Example: Slack notifier¶
async def slack_notify(approval_id: str, module_id: str, arguments: dict) -> None:
await slack_client.post_message(
channel="#approvals",
text=f"Approval needed for `{module_id}` (id: `{approval_id}`)\nArgs: {arguments}",
)
mcp = APCoreMCP("./extensions",
approval_store=InMemoryApprovalStore(),
approval_notify=slack_notify,
)
Production Store Guidance¶
InMemoryApprovalStore is not suitable for production. A production implementation must satisfy:
- Persistent storage — Records survive process restarts. Use a database (PostgreSQL, Redis, DynamoDB) or a durable key-value store.
- TTL / expiry on records — Expired records must be cleaned up automatically. Most storage backends (Redis TTL, DynamoDB TTL, SQL job) support this natively.
- Concurrent access safety — Multiple server instances must not corrupt each other's records.
resolve()in particular must be atomic: only the first call for a givenapproval_idtransitions the status; subsequent calls returnFalse. resolve()atomicity — Implement as a conditional write (e.g.,UPDATE ... WHERE status = 'pending'in SQL;SET NXor Lua script in Redis). Theboolreturn value depends on whether the row was actually updated.
Pseudocode: Redis-backed store¶
class RedisApprovalStore(ApprovalStore):
def __init__(self, redis: Redis, ttl_seconds: int = 86400):
self._redis = redis
self._ttl = ttl_seconds
async def save_pending(self, approval_id, module_id, arguments):
key = f"approval:{approval_id}"
record = {"approval_id": approval_id, "module_id": module_id, "status": "pending"}
# NX = only set if key does not exist (idempotency)
await self._redis.set(key, json.dumps(record), ex=self._ttl, nx=True)
async def get_result(self, approval_id):
raw = await self._redis.get(f"approval:{approval_id}")
return json.loads(raw) if raw else None
async def resolve(self, approval_id, approved, reason=None):
key = f"approval:{approval_id}"
# Atomic compare-and-swap via Lua script
status = "approved" if approved else "rejected"
script = """
local raw = redis.call('GET', KEYS[1])
if not raw then return 0 end
local rec = cjson.decode(raw)
if rec['status'] ~= 'pending' then return 0 end
rec['status'] = ARGV[1]
if ARGV[2] ~= '' then rec['reason'] = ARGV[2] end
rec['arguments'] = nil -- drop arguments after resolve
redis.call('SET', KEYS[1], cjson.encode(rec), 'KEEPTTL')
return 1
"""
result = await self._redis.eval(script, 1, key, status, reason or "")
return result == 1
Key properties of the script above:
- Returns 0 (→ False) if the key does not exist or the record is not pending.
- Drops arguments from the stored record after resolve to reclaim memory.
- Preserves TTL on the record so it expires naturally.
Cross-SDK Conformance Notes¶
All three SDKs (Python, TypeScript, Rust) implement identical wire-level behavior. The following invariants MUST hold across all implementations:
| Property | Value |
|---|---|
approval_id format |
UUID v4, generated by StorageBackedApprovalHandler (not the store) |
__apcore_approval_check tool name |
Exact string __apcore_approval_check |
APPROVAL_PENDING error wire key |
errorType: "APPROVAL_PENDING" |
approvalId in error details |
camelCase — details.approvalId (matches MCP/OpenAI convention) |
approval_id in meta-tool schema |
snake_case — input param and output field |
arguments in get_result() |
NOT returned (dropped after resolve) |
| Reserved tool prefix | __apcore_ — same as __apcore_task_* meta-tools |
is_error on unknown approval_id |
false — status field carries "rejected" |
is_error on missing approval_id param |
true |
Naming asymmetry¶
The camelCase / snake_case asymmetry between the error envelope (details.approvalId) and the meta-tool schema (approval_id) is intentional:
- The error envelope is part of the MCP wire protocol where camelCase is the convention.
- The meta-tool input schema is exposed as a tool argument, where snake_case matches apcore's module naming conventions and is consistent with the async task meta-tools (
task_id).
Contract: StorageBackedApprovalHandler.request_approval¶
Inputs¶
- request: ApprovalRequest, required, validates[has
module_id,argumentsfields]
Errors¶
- Returns
ApprovalResult(status="rejected", reason="Storage error")— whensave_pending()raises unexpectedly - Returns
ApprovalResult(status="rejected", reason="Store capacity exceeded")— when store raisesApprovalStorageCapacityError - Never raises; all failure modes return a rejected ApprovalResult
Returns¶
- On success:
ApprovalResult(status="pending", approval_id=<uuid4>)— always; the caller checks_meta.approvalIdto short-circuit on retry - The
approval_idis a freshly generated UUID v4 (generated before callingsave_pending)
Properties¶
- async: true
- thread_safe: true
- pure: false
- idempotent: false
Contract: StorageBackedApprovalHandler.check_approval¶
Called by apcore when the agent retries a call with
_meta.approvalIdset.
Inputs¶
- approval_id: str, required, validates[non-empty string]
Errors¶
- Returns
ApprovalResult(status="rejected", reason="Storage error")— whenget_result()raises - Returns
ApprovalResult(status="rejected", reason="Approval not found or expired")— whenget_result()returns None
Returns¶
- On success:
ApprovalResult(status="approved")when record status is"approved" - On rejection:
ApprovalResult(status="rejected", reason=<record.reason or "Approval rejected">)when record status is"rejected" - On pending:
ApprovalResult(status="rejected", reason="Approval still pending")— pending on retry is treated as rejection to prevent indefinite blocking
Properties¶
- async: true
- thread_safe: true
- pure: false
- idempotent: true
Contract: __apcore_approval_check handler¶
Internal handler — dispatched by the meta-tool router for tool name
__apcore_approval_check.
Inputs¶
- approval_id: str, required, validates[non-empty string], reject_with=error tuple (is_error=true)
Errors¶
- Returns
(content, is_error=True, None)with{"error": "INVALID_ARG", "message": "approval_id is required"}— when approval_id is missing or empty
Returns¶
- On success: tuple
(list[dict], is_error=False, None)— content is JSON-serialised{ "approval_id": str, "status": str, "reason"?: str } - Unknown approval_id: same tuple with
{ "approval_id": ..., "status": "rejected" }— is_error remains false - On storage read failure:
{ "approval_id": ..., "status": "rejected", "reason": "Storage error" }— is_error remains false; failure is logged at warning level
Properties¶
- async: true
- thread_safe: true
- pure: false
- idempotent: true