foundry-mcp 0.3.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. foundry_mcp/__init__.py +7 -0
  2. foundry_mcp/cli/__init__.py +80 -0
  3. foundry_mcp/cli/__main__.py +9 -0
  4. foundry_mcp/cli/agent.py +96 -0
  5. foundry_mcp/cli/commands/__init__.py +37 -0
  6. foundry_mcp/cli/commands/cache.py +137 -0
  7. foundry_mcp/cli/commands/dashboard.py +148 -0
  8. foundry_mcp/cli/commands/dev.py +446 -0
  9. foundry_mcp/cli/commands/journal.py +377 -0
  10. foundry_mcp/cli/commands/lifecycle.py +274 -0
  11. foundry_mcp/cli/commands/modify.py +824 -0
  12. foundry_mcp/cli/commands/plan.py +633 -0
  13. foundry_mcp/cli/commands/pr.py +393 -0
  14. foundry_mcp/cli/commands/review.py +652 -0
  15. foundry_mcp/cli/commands/session.py +479 -0
  16. foundry_mcp/cli/commands/specs.py +856 -0
  17. foundry_mcp/cli/commands/tasks.py +807 -0
  18. foundry_mcp/cli/commands/testing.py +676 -0
  19. foundry_mcp/cli/commands/validate.py +982 -0
  20. foundry_mcp/cli/config.py +98 -0
  21. foundry_mcp/cli/context.py +259 -0
  22. foundry_mcp/cli/flags.py +266 -0
  23. foundry_mcp/cli/logging.py +212 -0
  24. foundry_mcp/cli/main.py +44 -0
  25. foundry_mcp/cli/output.py +122 -0
  26. foundry_mcp/cli/registry.py +110 -0
  27. foundry_mcp/cli/resilience.py +178 -0
  28. foundry_mcp/cli/transcript.py +217 -0
  29. foundry_mcp/config.py +850 -0
  30. foundry_mcp/core/__init__.py +144 -0
  31. foundry_mcp/core/ai_consultation.py +1636 -0
  32. foundry_mcp/core/cache.py +195 -0
  33. foundry_mcp/core/capabilities.py +446 -0
  34. foundry_mcp/core/concurrency.py +898 -0
  35. foundry_mcp/core/context.py +540 -0
  36. foundry_mcp/core/discovery.py +1603 -0
  37. foundry_mcp/core/error_collection.py +728 -0
  38. foundry_mcp/core/error_store.py +592 -0
  39. foundry_mcp/core/feature_flags.py +592 -0
  40. foundry_mcp/core/health.py +749 -0
  41. foundry_mcp/core/journal.py +694 -0
  42. foundry_mcp/core/lifecycle.py +412 -0
  43. foundry_mcp/core/llm_config.py +1350 -0
  44. foundry_mcp/core/llm_patterns.py +510 -0
  45. foundry_mcp/core/llm_provider.py +1569 -0
  46. foundry_mcp/core/logging_config.py +374 -0
  47. foundry_mcp/core/metrics_persistence.py +584 -0
  48. foundry_mcp/core/metrics_registry.py +327 -0
  49. foundry_mcp/core/metrics_store.py +641 -0
  50. foundry_mcp/core/modifications.py +224 -0
  51. foundry_mcp/core/naming.py +123 -0
  52. foundry_mcp/core/observability.py +1216 -0
  53. foundry_mcp/core/otel.py +452 -0
  54. foundry_mcp/core/otel_stubs.py +264 -0
  55. foundry_mcp/core/pagination.py +255 -0
  56. foundry_mcp/core/progress.py +317 -0
  57. foundry_mcp/core/prometheus.py +577 -0
  58. foundry_mcp/core/prompts/__init__.py +464 -0
  59. foundry_mcp/core/prompts/fidelity_review.py +546 -0
  60. foundry_mcp/core/prompts/markdown_plan_review.py +511 -0
  61. foundry_mcp/core/prompts/plan_review.py +623 -0
  62. foundry_mcp/core/providers/__init__.py +225 -0
  63. foundry_mcp/core/providers/base.py +476 -0
  64. foundry_mcp/core/providers/claude.py +460 -0
  65. foundry_mcp/core/providers/codex.py +619 -0
  66. foundry_mcp/core/providers/cursor_agent.py +642 -0
  67. foundry_mcp/core/providers/detectors.py +488 -0
  68. foundry_mcp/core/providers/gemini.py +405 -0
  69. foundry_mcp/core/providers/opencode.py +616 -0
  70. foundry_mcp/core/providers/opencode_wrapper.js +302 -0
  71. foundry_mcp/core/providers/package-lock.json +24 -0
  72. foundry_mcp/core/providers/package.json +25 -0
  73. foundry_mcp/core/providers/registry.py +607 -0
  74. foundry_mcp/core/providers/test_provider.py +171 -0
  75. foundry_mcp/core/providers/validation.py +729 -0
  76. foundry_mcp/core/rate_limit.py +427 -0
  77. foundry_mcp/core/resilience.py +600 -0
  78. foundry_mcp/core/responses.py +934 -0
  79. foundry_mcp/core/review.py +366 -0
  80. foundry_mcp/core/security.py +438 -0
  81. foundry_mcp/core/spec.py +1650 -0
  82. foundry_mcp/core/task.py +1289 -0
  83. foundry_mcp/core/testing.py +450 -0
  84. foundry_mcp/core/validation.py +2081 -0
  85. foundry_mcp/dashboard/__init__.py +32 -0
  86. foundry_mcp/dashboard/app.py +119 -0
  87. foundry_mcp/dashboard/components/__init__.py +17 -0
  88. foundry_mcp/dashboard/components/cards.py +88 -0
  89. foundry_mcp/dashboard/components/charts.py +234 -0
  90. foundry_mcp/dashboard/components/filters.py +136 -0
  91. foundry_mcp/dashboard/components/tables.py +195 -0
  92. foundry_mcp/dashboard/data/__init__.py +11 -0
  93. foundry_mcp/dashboard/data/stores.py +433 -0
  94. foundry_mcp/dashboard/launcher.py +289 -0
  95. foundry_mcp/dashboard/views/__init__.py +12 -0
  96. foundry_mcp/dashboard/views/errors.py +217 -0
  97. foundry_mcp/dashboard/views/metrics.py +174 -0
  98. foundry_mcp/dashboard/views/overview.py +160 -0
  99. foundry_mcp/dashboard/views/providers.py +83 -0
  100. foundry_mcp/dashboard/views/sdd_workflow.py +255 -0
  101. foundry_mcp/dashboard/views/tool_usage.py +139 -0
  102. foundry_mcp/prompts/__init__.py +9 -0
  103. foundry_mcp/prompts/workflows.py +525 -0
  104. foundry_mcp/resources/__init__.py +9 -0
  105. foundry_mcp/resources/specs.py +591 -0
  106. foundry_mcp/schemas/__init__.py +38 -0
  107. foundry_mcp/schemas/sdd-spec-schema.json +386 -0
  108. foundry_mcp/server.py +164 -0
  109. foundry_mcp/tools/__init__.py +10 -0
  110. foundry_mcp/tools/unified/__init__.py +71 -0
  111. foundry_mcp/tools/unified/authoring.py +1487 -0
  112. foundry_mcp/tools/unified/context_helpers.py +98 -0
  113. foundry_mcp/tools/unified/documentation_helpers.py +198 -0
  114. foundry_mcp/tools/unified/environment.py +939 -0
  115. foundry_mcp/tools/unified/error.py +462 -0
  116. foundry_mcp/tools/unified/health.py +225 -0
  117. foundry_mcp/tools/unified/journal.py +841 -0
  118. foundry_mcp/tools/unified/lifecycle.py +632 -0
  119. foundry_mcp/tools/unified/metrics.py +777 -0
  120. foundry_mcp/tools/unified/plan.py +745 -0
  121. foundry_mcp/tools/unified/pr.py +294 -0
  122. foundry_mcp/tools/unified/provider.py +629 -0
  123. foundry_mcp/tools/unified/review.py +685 -0
  124. foundry_mcp/tools/unified/review_helpers.py +299 -0
  125. foundry_mcp/tools/unified/router.py +102 -0
  126. foundry_mcp/tools/unified/server.py +580 -0
  127. foundry_mcp/tools/unified/spec.py +808 -0
  128. foundry_mcp/tools/unified/task.py +2202 -0
  129. foundry_mcp/tools/unified/test.py +370 -0
  130. foundry_mcp/tools/unified/verification.py +520 -0
  131. foundry_mcp-0.3.3.dist-info/METADATA +337 -0
  132. foundry_mcp-0.3.3.dist-info/RECORD +135 -0
  133. foundry_mcp-0.3.3.dist-info/WHEEL +4 -0
  134. foundry_mcp-0.3.3.dist-info/entry_points.txt +3 -0
  135. foundry_mcp-0.3.3.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,934 @@
1
+ """
2
+ Standard response contracts for MCP tool operations.
3
+ Provides consistent response structures across all foundry-mcp tools.
4
+
5
+ Response Schema Contract
6
+ ========================
7
+
8
+ All MCP tool responses follow a standard structure:
9
+
10
+ {
11
+ "success": bool, # Required: operation success/failure
12
+ "data": {...}, # Required: primary payload (empty dict on error)
13
+ "error": str | null, # Required: error message or null on success
14
+ "meta": { # Required: response metadata
15
+ "version": "response-v2",
16
+ "request_id": "req_abc123"?,
17
+ "warnings": ["..."]?,
18
+ "pagination": { ... }?,
19
+ "rate_limit": { ... }?,
20
+ "telemetry": { ... }?
21
+ }
22
+ }
23
+
24
+ Metadata Semantics
25
+ ------------------
26
+
27
+ Attach operational context through `meta` so every tool shares an identical
28
+ envelope. The standard keys are:
29
+
30
+ * `version` *(required)* – identifies the contract version (`response-v2`).
31
+ * `request_id` *(should)* – correlation identifier propagated through logs.
32
+ * `warnings` *(should)* – array of non-fatal issues for successful operations.
33
+ * `pagination` *(may)* – cursor information (`cursor`, `has_more`, `total_count`).
34
+ * `rate_limit` *(may)* – limit, remaining, reset timestamp, retry hints.
35
+ * `telemetry` *(may)* – timing/performance metrics, downstream call counts, etc.
36
+
37
+ Multi-Payload Tools
38
+ -------------------
39
+
40
+ Tools returning multiple payloads should nest each value under a named key:
41
+
42
+ data = {
43
+ "spec": {...}, # First payload
44
+ "tasks": [...], # Second payload
45
+ }
46
+
47
+ This ensures consumers can access each payload by name rather than relying
48
+ on position or implicit structure.
49
+
50
+ Edge Cases & Partial Payloads
51
+ -----------------------------
52
+
53
+ Empty Results (success=True):
54
+ When a query succeeds but finds no results, return success=True with
55
+ empty/partial data to distinguish from errors:
56
+
57
+ {"success": True, "data": {"tasks": [], "count": 0}, "error": None}
58
+
59
+ Not Found (success=False):
60
+ When the requested resource doesn't exist, return success=False:
61
+
62
+ {"success": False, "data": {}, "error": "Spec not found: my-spec"}
63
+
64
+ Blocked/Conditional States (success=True):
65
+ Dependency checks and similar queries return success=True with state info:
66
+
67
+ {
68
+ "success": True,
69
+ "data": {
70
+ "task_id": "task-1-2",
71
+ "can_start": False,
72
+ "blocked_by": [{"id": "task-1-1", "status": "pending"}]
73
+ },
74
+ "error": None,
75
+ "meta": {
76
+ "version": "response-v2",
77
+ "warnings": ["Task currently blocked"]
78
+ }
79
+ }
80
+
81
+ Key Principle:
82
+ - `success=True` means the operation executed correctly (even if the result is empty).
83
+ - `success=False` means the operation failed to execute; include actionable error details.
84
+ - Keep business data inside `data` and operational context inside `meta`.
85
+ """
86
+
87
+ import json
88
+ import logging
89
+ import subprocess
90
+ from dataclasses import dataclass, field
91
+ from enum import Enum
92
+ from typing import Any, Dict, Mapping, Optional, Sequence, Union
93
+
94
+ from foundry_mcp.core.context import get_correlation_id
95
+
96
+ logger = logging.getLogger(__name__)
97
+
98
+
99
+ class ErrorCode(str, Enum):
100
+ """Machine-readable error codes for MCP tool responses.
101
+
102
+ Use these canonical codes in `error_code` fields to enable consistent
103
+ client-side error handling. Codes follow SCREAMING_SNAKE_CASE convention.
104
+
105
+ Categories:
106
+ - Validation (input errors)
107
+ - Resource (not found, conflict)
108
+ - Access (auth, permissions, rate limits)
109
+ - System (internal, unavailable)
110
+ """
111
+
112
+ # Validation errors
113
+ VALIDATION_ERROR = "VALIDATION_ERROR"
114
+ INVALID_FORMAT = "INVALID_FORMAT"
115
+ MISSING_REQUIRED = "MISSING_REQUIRED"
116
+
117
+ # Resource errors
118
+ NOT_FOUND = "NOT_FOUND"
119
+ SPEC_NOT_FOUND = "SPEC_NOT_FOUND"
120
+ TASK_NOT_FOUND = "TASK_NOT_FOUND"
121
+ PHASE_NOT_FOUND = "PHASE_NOT_FOUND"
122
+ DUPLICATE_ENTRY = "DUPLICATE_ENTRY"
123
+ CONFLICT = "CONFLICT"
124
+
125
+ # Access errors
126
+ UNAUTHORIZED = "UNAUTHORIZED"
127
+ FORBIDDEN = "FORBIDDEN"
128
+ RATE_LIMIT_EXCEEDED = "RATE_LIMIT_EXCEEDED"
129
+ FEATURE_DISABLED = "FEATURE_DISABLED"
130
+
131
+ # System errors
132
+ INTERNAL_ERROR = "INTERNAL_ERROR"
133
+ UNAVAILABLE = "UNAVAILABLE"
134
+
135
+ # AI/LLM Provider errors
136
+ AI_NO_PROVIDER = "AI_NO_PROVIDER"
137
+ AI_PROVIDER_TIMEOUT = "AI_PROVIDER_TIMEOUT"
138
+ AI_PROVIDER_ERROR = "AI_PROVIDER_ERROR"
139
+ AI_CONTEXT_TOO_LARGE = "AI_CONTEXT_TOO_LARGE"
140
+ AI_PROMPT_NOT_FOUND = "AI_PROMPT_NOT_FOUND"
141
+ AI_CACHE_STALE = "AI_CACHE_STALE"
142
+
143
+
144
+ class ErrorType(str, Enum):
145
+ """Error categories for routing and client-side handling.
146
+
147
+ Each type corresponds to an HTTP status code analog and indicates
148
+ whether the operation should be retried.
149
+
150
+ See docs/codebase_standards/mcp_response_schema.md for the full mapping.
151
+ """
152
+
153
+ VALIDATION = "validation" # 400 - No retry, fix input
154
+ AUTHENTICATION = "authentication" # 401 - No retry, re-authenticate
155
+ AUTHORIZATION = "authorization" # 403 - No retry
156
+ NOT_FOUND = "not_found" # 404 - No retry
157
+ CONFLICT = "conflict" # 409 - Maybe retry, check state
158
+ RATE_LIMIT = "rate_limit" # 429 - Yes, after delay
159
+ FEATURE_FLAG = "feature_flag" # 403 - No retry, check flag status
160
+ INTERNAL = "internal" # 500 - Yes, with backoff
161
+ UNAVAILABLE = "unavailable" # 503 - Yes, with backoff
162
+ AI_PROVIDER = "ai_provider" # AI-specific - Retry varies by error
163
+
164
+
165
+ @dataclass
166
+ class ToolResponse:
167
+ """
168
+ Standard response structure for MCP tool operations.
169
+
170
+ All tool handlers should return data that can be serialized to this format,
171
+ ensuring consistent API responses across the codebase.
172
+
173
+ Attributes:
174
+ success: Whether the operation completed successfully
175
+ data: The primary payload (operation-specific structured data)
176
+ error: Error message if success is False, None otherwise
177
+ meta: Response metadata including version identifier
178
+ """
179
+
180
+ success: bool
181
+ data: Dict[str, Any] = field(default_factory=dict)
182
+ error: Optional[str] = None
183
+ meta: Dict[str, Any] = field(default_factory=lambda: {"version": "response-v2"})
184
+
185
+
186
+ def _build_meta(
187
+ *,
188
+ request_id: Optional[str] = None,
189
+ warnings: Optional[Sequence[str]] = None,
190
+ pagination: Optional[Mapping[str, Any]] = None,
191
+ rate_limit: Optional[Mapping[str, Any]] = None,
192
+ telemetry: Optional[Mapping[str, Any]] = None,
193
+ extra: Optional[Mapping[str, Any]] = None,
194
+ auto_inject_request_id: bool = True,
195
+ ) -> Dict[str, Any]:
196
+ """Construct a metadata payload that always includes the response version.
197
+
198
+ Args:
199
+ request_id: Explicit correlation ID (takes precedence if provided)
200
+ warnings: Non-fatal issues to surface
201
+ pagination: Cursor metadata for list results
202
+ rate_limit: Rate limit state
203
+ telemetry: Timing/performance metadata
204
+ extra: Arbitrary extra metadata to merge
205
+ auto_inject_request_id: If True (default), auto-inject correlation_id
206
+ from context when request_id is not explicitly provided
207
+ """
208
+ meta: Dict[str, Any] = {"version": "response-v2"}
209
+
210
+ # Auto-inject request_id from context if not explicitly provided
211
+ effective_request_id = request_id
212
+ if effective_request_id is None and auto_inject_request_id:
213
+ effective_request_id = get_correlation_id() or None
214
+
215
+ if effective_request_id:
216
+ meta["request_id"] = effective_request_id
217
+ if warnings:
218
+ meta["warnings"] = list(warnings)
219
+ if pagination:
220
+ meta["pagination"] = dict(pagination)
221
+ if rate_limit:
222
+ meta["rate_limit"] = dict(rate_limit)
223
+ if telemetry:
224
+ meta["telemetry"] = dict(telemetry)
225
+ if extra:
226
+ meta.update(dict(extra))
227
+
228
+ return meta
229
+
230
+
231
+ def success_response(
232
+ data: Optional[Mapping[str, Any]] = None,
233
+ *,
234
+ warnings: Optional[Sequence[str]] = None,
235
+ pagination: Optional[Mapping[str, Any]] = None,
236
+ rate_limit: Optional[Mapping[str, Any]] = None,
237
+ telemetry: Optional[Mapping[str, Any]] = None,
238
+ request_id: Optional[str] = None,
239
+ meta: Optional[Mapping[str, Any]] = None,
240
+ **fields: Any,
241
+ ) -> ToolResponse:
242
+ """Create a standardized success response.
243
+
244
+ Args:
245
+ data: Optional mapping used as the base payload.
246
+ warnings: Non-fatal issues to surface in ``meta.warnings``.
247
+ pagination: Cursor metadata for list results.
248
+ rate_limit: Rate limit state (limit, remaining, reset_at, etc.).
249
+ telemetry: Timing/performance metadata.
250
+ request_id: Correlation identifier propagated through logs/traces.
251
+ meta: Arbitrary extra metadata to merge into ``meta``.
252
+ **fields: Additional payload fields (shorthand for ``data.update``).
253
+ """
254
+ payload: Dict[str, Any] = {}
255
+ if data:
256
+ payload.update(dict(data))
257
+ if fields:
258
+ payload.update(fields)
259
+
260
+ meta_payload = _build_meta(
261
+ request_id=request_id,
262
+ warnings=warnings,
263
+ pagination=pagination,
264
+ rate_limit=rate_limit,
265
+ telemetry=telemetry,
266
+ extra=meta,
267
+ )
268
+
269
+ return ToolResponse(success=True, data=payload, error=None, meta=meta_payload)
270
+
271
+
272
+ def error_response(
273
+ message: str,
274
+ *,
275
+ data: Optional[Mapping[str, Any]] = None,
276
+ error_code: Optional[Union[ErrorCode, str]] = None,
277
+ error_type: Optional[Union[ErrorType, str]] = None,
278
+ remediation: Optional[str] = None,
279
+ details: Optional[Mapping[str, Any]] = None,
280
+ request_id: Optional[str] = None,
281
+ rate_limit: Optional[Mapping[str, Any]] = None,
282
+ telemetry: Optional[Mapping[str, Any]] = None,
283
+ meta: Optional[Mapping[str, Any]] = None,
284
+ ) -> ToolResponse:
285
+ """Create a standardized error response.
286
+
287
+ Args:
288
+ message: Human-readable description of the failure.
289
+ data: Optional mapping with additional machine-readable context.
290
+ error_code: Canonical error code (use ``ErrorCode`` enum or string,
291
+ e.g., ``ErrorCode.VALIDATION_ERROR`` or ``"VALIDATION_ERROR"``).
292
+ error_type: Error category for routing (use ``ErrorType`` enum or string,
293
+ e.g., ``ErrorType.VALIDATION`` or ``"validation"``).
294
+ remediation: User-facing guidance on how to fix the issue.
295
+ details: Nested structure describing validation failures or metadata.
296
+ request_id: Correlation identifier propagated through logs/traces.
297
+ rate_limit: Rate limit state to help clients back off correctly.
298
+ telemetry: Timing/performance metadata captured before failure.
299
+ meta: Arbitrary extra metadata to merge into ``meta``.
300
+
301
+ Example:
302
+ >>> error_response(
303
+ ... "Validation failed: spec_id is required",
304
+ ... error_code=ErrorCode.MISSING_REQUIRED,
305
+ ... error_type=ErrorType.VALIDATION,
306
+ ... remediation="Provide a non-empty spec_id parameter",
307
+ ... )
308
+ """
309
+ payload: Dict[str, Any] = {}
310
+ if data:
311
+ payload.update(dict(data))
312
+
313
+ effective_error_code: Union[ErrorCode, str] = (
314
+ error_code if error_code is not None else ErrorCode.INTERNAL_ERROR
315
+ )
316
+ effective_error_type: Union[ErrorType, str] = (
317
+ error_type if error_type is not None else ErrorType.INTERNAL
318
+ )
319
+
320
+ if "error_code" not in payload:
321
+ payload["error_code"] = (
322
+ effective_error_code.value
323
+ if isinstance(effective_error_code, Enum)
324
+ else effective_error_code
325
+ )
326
+ if "error_type" not in payload:
327
+ payload["error_type"] = (
328
+ effective_error_type.value
329
+ if isinstance(effective_error_type, Enum)
330
+ else effective_error_type
331
+ )
332
+ if remediation is not None and "remediation" not in payload:
333
+ payload["remediation"] = remediation
334
+ if details and "details" not in payload:
335
+ payload["details"] = dict(details)
336
+
337
+ meta_payload = _build_meta(
338
+ request_id=request_id,
339
+ rate_limit=rate_limit,
340
+ telemetry=telemetry,
341
+ extra=meta,
342
+ )
343
+
344
+ return ToolResponse(success=False, data=payload, error=message, meta=meta_payload)
345
+
346
+
347
+ # ---------------------------------------------------------------------------
348
+ # Specialized Error Helpers
349
+ # ---------------------------------------------------------------------------
350
+
351
+
352
+ def validation_error(
353
+ message: str,
354
+ *,
355
+ field: Optional[str] = None,
356
+ details: Optional[Mapping[str, Any]] = None,
357
+ remediation: Optional[str] = None,
358
+ request_id: Optional[str] = None,
359
+ ) -> ToolResponse:
360
+ """Create a validation error response (HTTP 400 analog).
361
+
362
+ Args:
363
+ message: Human-readable description of the validation failure.
364
+ field: The field that failed validation.
365
+ details: Additional context (e.g., constraint violated, value received).
366
+ remediation: Guidance on how to fix the input.
367
+ request_id: Correlation identifier.
368
+
369
+ Example:
370
+ >>> validation_error(
371
+ ... "Invalid email format",
372
+ ... field="email",
373
+ ... remediation="Provide email in format: user@domain.com",
374
+ ... )
375
+ """
376
+ error_details = dict(details) if details else {}
377
+ if field and "field" not in error_details:
378
+ error_details["field"] = field
379
+
380
+ return error_response(
381
+ message,
382
+ error_code=ErrorCode.VALIDATION_ERROR,
383
+ error_type=ErrorType.VALIDATION,
384
+ details=error_details if error_details else None,
385
+ remediation=remediation,
386
+ request_id=request_id,
387
+ )
388
+
389
+
390
+ def not_found_error(
391
+ resource_type: str,
392
+ resource_id: str,
393
+ *,
394
+ remediation: Optional[str] = None,
395
+ request_id: Optional[str] = None,
396
+ ) -> ToolResponse:
397
+ """Create a not found error response (HTTP 404 analog).
398
+
399
+ Args:
400
+ resource_type: Type of resource (e.g., "Spec", "Task", "User").
401
+ resource_id: Identifier of the missing resource.
402
+ remediation: Guidance on how to resolve (defaults to verification hint).
403
+ request_id: Correlation identifier.
404
+
405
+ Example:
406
+ >>> not_found_error("Spec", "my-spec-001")
407
+ """
408
+ return error_response(
409
+ f"{resource_type} '{resource_id}' not found",
410
+ error_code=ErrorCode.NOT_FOUND,
411
+ error_type=ErrorType.NOT_FOUND,
412
+ data={"resource_type": resource_type, "resource_id": resource_id},
413
+ remediation=remediation or f"Verify the {resource_type.lower()} ID exists.",
414
+ request_id=request_id,
415
+ )
416
+
417
+
418
+ def rate_limit_error(
419
+ limit: int,
420
+ period: str,
421
+ retry_after_seconds: int,
422
+ *,
423
+ remediation: Optional[str] = None,
424
+ request_id: Optional[str] = None,
425
+ ) -> ToolResponse:
426
+ """Create a rate limit error response (HTTP 429 analog).
427
+
428
+ Args:
429
+ limit: Maximum requests allowed in the period.
430
+ period: Time window (e.g., "minute", "hour").
431
+ retry_after_seconds: Seconds until client can retry.
432
+ remediation: Guidance on how to proceed.
433
+ request_id: Correlation identifier.
434
+
435
+ Example:
436
+ >>> rate_limit_error(100, "minute", 45)
437
+ """
438
+ return error_response(
439
+ f"Rate limit exceeded: {limit} requests per {period}",
440
+ error_code=ErrorCode.RATE_LIMIT_EXCEEDED,
441
+ error_type=ErrorType.RATE_LIMIT,
442
+ data={"retry_after_seconds": retry_after_seconds},
443
+ rate_limit={
444
+ "limit": limit,
445
+ "period": period,
446
+ "retry_after": retry_after_seconds,
447
+ },
448
+ remediation=remediation
449
+ or f"Wait {retry_after_seconds} seconds before retrying.",
450
+ request_id=request_id,
451
+ )
452
+
453
+
454
+ def unauthorized_error(
455
+ message: str = "Authentication required",
456
+ *,
457
+ remediation: Optional[str] = None,
458
+ request_id: Optional[str] = None,
459
+ ) -> ToolResponse:
460
+ """Create an unauthorized error response (HTTP 401 analog).
461
+
462
+ Args:
463
+ message: Human-readable description.
464
+ remediation: Guidance on how to authenticate.
465
+ request_id: Correlation identifier.
466
+
467
+ Example:
468
+ >>> unauthorized_error("Invalid API key")
469
+ """
470
+ return error_response(
471
+ message,
472
+ error_code=ErrorCode.UNAUTHORIZED,
473
+ error_type=ErrorType.AUTHENTICATION,
474
+ remediation=remediation or "Provide valid authentication credentials.",
475
+ request_id=request_id,
476
+ )
477
+
478
+
479
+ def forbidden_error(
480
+ message: str,
481
+ *,
482
+ required_permission: Optional[str] = None,
483
+ remediation: Optional[str] = None,
484
+ request_id: Optional[str] = None,
485
+ ) -> ToolResponse:
486
+ """Create a forbidden error response (HTTP 403 analog).
487
+
488
+ Args:
489
+ message: Human-readable description.
490
+ required_permission: The permission needed for this operation.
491
+ remediation: Guidance on how to obtain access.
492
+ request_id: Correlation identifier.
493
+
494
+ Example:
495
+ >>> forbidden_error(
496
+ ... "Cannot delete project",
497
+ ... required_permission="project:delete",
498
+ ... )
499
+ """
500
+ data: Dict[str, Any] = {}
501
+ if required_permission:
502
+ data["required_permission"] = required_permission
503
+
504
+ return error_response(
505
+ message,
506
+ error_code=ErrorCode.FORBIDDEN,
507
+ error_type=ErrorType.AUTHORIZATION,
508
+ data=data if data else None,
509
+ remediation=remediation
510
+ or "Request appropriate permissions from the resource owner.",
511
+ request_id=request_id,
512
+ )
513
+
514
+
515
+ def conflict_error(
516
+ message: str,
517
+ *,
518
+ details: Optional[Mapping[str, Any]] = None,
519
+ remediation: Optional[str] = None,
520
+ request_id: Optional[str] = None,
521
+ ) -> ToolResponse:
522
+ """Create a conflict error response (HTTP 409 analog).
523
+
524
+ Args:
525
+ message: Human-readable description of the conflict.
526
+ details: Context about the conflicting state.
527
+ remediation: Guidance on how to resolve the conflict.
528
+ request_id: Correlation identifier.
529
+
530
+ Example:
531
+ >>> conflict_error(
532
+ ... "Resource already exists",
533
+ ... details={"existing_id": "spec-001"},
534
+ ... )
535
+ """
536
+ return error_response(
537
+ message,
538
+ error_code=ErrorCode.CONFLICT,
539
+ error_type=ErrorType.CONFLICT,
540
+ details=details,
541
+ remediation=remediation or "Check current state and retry if appropriate.",
542
+ request_id=request_id,
543
+ )
544
+
545
+
546
+ def internal_error(
547
+ message: str = "An internal error occurred",
548
+ *,
549
+ request_id: Optional[str] = None,
550
+ ) -> ToolResponse:
551
+ """Create an internal error response (HTTP 500 analog).
552
+
553
+ Args:
554
+ message: Human-readable description (keep vague for security).
555
+ request_id: Correlation identifier for log correlation.
556
+
557
+ Example:
558
+ >>> internal_error(request_id="req_abc123")
559
+ """
560
+ remediation = "Please try again. If the problem persists, contact support."
561
+ if request_id:
562
+ remediation += f" Reference: {request_id}"
563
+
564
+ return error_response(
565
+ message,
566
+ error_code=ErrorCode.INTERNAL_ERROR,
567
+ error_type=ErrorType.INTERNAL,
568
+ remediation=remediation,
569
+ request_id=request_id,
570
+ )
571
+
572
+
573
+ def unavailable_error(
574
+ message: str = "Service temporarily unavailable",
575
+ *,
576
+ retry_after_seconds: Optional[int] = None,
577
+ request_id: Optional[str] = None,
578
+ ) -> ToolResponse:
579
+ """Create an unavailable error response (HTTP 503 analog).
580
+
581
+ Args:
582
+ message: Human-readable description.
583
+ retry_after_seconds: Suggested retry delay.
584
+ request_id: Correlation identifier.
585
+
586
+ Example:
587
+ >>> unavailable_error("Database maintenance in progress", retry_after_seconds=300)
588
+ """
589
+ data: Dict[str, Any] = {}
590
+ if retry_after_seconds:
591
+ data["retry_after_seconds"] = retry_after_seconds
592
+
593
+ remediation = "Please retry with exponential backoff."
594
+ if retry_after_seconds:
595
+ remediation = f"Retry after {retry_after_seconds} seconds."
596
+
597
+ return error_response(
598
+ message,
599
+ error_code=ErrorCode.UNAVAILABLE,
600
+ error_type=ErrorType.UNAVAILABLE,
601
+ data=data if data else None,
602
+ remediation=remediation,
603
+ request_id=request_id,
604
+ )
605
+
606
+
607
+ # ---------------------------------------------------------------------------
608
+ # AI/LLM Provider Error Helpers
609
+ # ---------------------------------------------------------------------------
610
+
611
+
612
+ def ai_no_provider_error(
613
+ message: str = "No AI provider available",
614
+ *,
615
+ required_providers: Optional[Sequence[str]] = None,
616
+ remediation: Optional[str] = None,
617
+ request_id: Optional[str] = None,
618
+ ) -> ToolResponse:
619
+ """Create an error response for when no AI provider is available.
620
+
621
+ Use when an AI consultation is requested but no providers are configured
622
+ or all configured providers have failed availability checks.
623
+
624
+ Args:
625
+ message: Human-readable description.
626
+ required_providers: List of provider IDs that were checked.
627
+ remediation: Guidance on how to configure a provider.
628
+ request_id: Correlation identifier.
629
+
630
+ Example:
631
+ >>> ai_no_provider_error(
632
+ ... "No AI provider available for plan review",
633
+ ... required_providers=["gemini", "cursor-agent", "codex"],
634
+ ... )
635
+ """
636
+ data: Dict[str, Any] = {}
637
+ if required_providers:
638
+ data["required_providers"] = list(required_providers)
639
+
640
+ default_remediation = (
641
+ "Configure an AI provider: set GEMINI_API_KEY, OPENAI_API_KEY, "
642
+ "or ANTHROPIC_API_KEY environment variable, or ensure cursor-agent is available."
643
+ )
644
+
645
+ return error_response(
646
+ message,
647
+ error_code=ErrorCode.AI_NO_PROVIDER,
648
+ error_type=ErrorType.AI_PROVIDER,
649
+ data=data if data else None,
650
+ remediation=remediation or default_remediation,
651
+ request_id=request_id,
652
+ )
653
+
654
+
655
+ def ai_provider_timeout_error(
656
+ provider_id: str,
657
+ timeout_seconds: int,
658
+ *,
659
+ message: Optional[str] = None,
660
+ remediation: Optional[str] = None,
661
+ request_id: Optional[str] = None,
662
+ ) -> ToolResponse:
663
+ """Create an error response for AI provider execution timeout.
664
+
665
+ Use when an AI provider call exceeds the configured timeout limit.
666
+
667
+ Args:
668
+ provider_id: The provider that timed out (e.g., "gemini", "codex").
669
+ timeout_seconds: The timeout that was exceeded.
670
+ message: Human-readable description (auto-generated if not provided).
671
+ remediation: Guidance on how to handle the timeout.
672
+ request_id: Correlation identifier.
673
+
674
+ Example:
675
+ >>> ai_provider_timeout_error("gemini", 300)
676
+ """
677
+ default_message = f"AI provider '{provider_id}' timed out after {timeout_seconds}s"
678
+
679
+ return error_response(
680
+ message or default_message,
681
+ error_code=ErrorCode.AI_PROVIDER_TIMEOUT,
682
+ error_type=ErrorType.AI_PROVIDER,
683
+ data={
684
+ "provider_id": provider_id,
685
+ "timeout_seconds": timeout_seconds,
686
+ },
687
+ remediation=remediation
688
+ or (
689
+ "Try again with a smaller context, increase the timeout, "
690
+ "or use a different provider."
691
+ ),
692
+ request_id=request_id,
693
+ )
694
+
695
+
696
+ def ai_provider_error(
697
+ provider_id: str,
698
+ error_detail: str,
699
+ *,
700
+ status_code: Optional[int] = None,
701
+ remediation: Optional[str] = None,
702
+ request_id: Optional[str] = None,
703
+ ) -> ToolResponse:
704
+ """Create an error response for when an AI provider returns an error.
705
+
706
+ Use when an AI provider API call fails with an error response.
707
+
708
+ Args:
709
+ provider_id: The provider that returned the error.
710
+ error_detail: The error message from the provider.
711
+ status_code: HTTP status code from the provider (if applicable).
712
+ remediation: Guidance on how to resolve the issue.
713
+ request_id: Correlation identifier.
714
+
715
+ Example:
716
+ >>> ai_provider_error("gemini", "Invalid API key", status_code=401)
717
+ """
718
+ data: Dict[str, Any] = {
719
+ "provider_id": provider_id,
720
+ "error_detail": error_detail,
721
+ }
722
+ if status_code is not None:
723
+ data["status_code"] = status_code
724
+
725
+ return error_response(
726
+ f"AI provider '{provider_id}' returned error: {error_detail}",
727
+ error_code=ErrorCode.AI_PROVIDER_ERROR,
728
+ error_type=ErrorType.AI_PROVIDER,
729
+ data=data,
730
+ remediation=remediation
731
+ or (
732
+ "Check provider configuration and API key validity. "
733
+ "Consult provider documentation for error details."
734
+ ),
735
+ request_id=request_id,
736
+ )
737
+
738
+
739
+ def ai_context_too_large_error(
740
+ context_tokens: int,
741
+ max_tokens: int,
742
+ *,
743
+ provider_id: Optional[str] = None,
744
+ remediation: Optional[str] = None,
745
+ request_id: Optional[str] = None,
746
+ ) -> ToolResponse:
747
+ """Create an error response for when context exceeds model limits.
748
+
749
+ Use when the prompt/context size exceeds the AI model's token limit.
750
+
751
+ Args:
752
+ context_tokens: Number of tokens in the attempted context.
753
+ max_tokens: Maximum tokens allowed by the model.
754
+ provider_id: The provider that rejected the context.
755
+ remediation: Guidance on how to reduce context size.
756
+ request_id: Correlation identifier.
757
+
758
+ Example:
759
+ >>> ai_context_too_large_error(150000, 128000, provider_id="gemini")
760
+ """
761
+ data: Dict[str, Any] = {
762
+ "context_tokens": context_tokens,
763
+ "max_tokens": max_tokens,
764
+ "overflow_tokens": context_tokens - max_tokens,
765
+ }
766
+ if provider_id:
767
+ data["provider_id"] = provider_id
768
+
769
+ return error_response(
770
+ f"Context size ({context_tokens} tokens) exceeds limit ({max_tokens} tokens)",
771
+ error_code=ErrorCode.AI_CONTEXT_TOO_LARGE,
772
+ error_type=ErrorType.AI_PROVIDER,
773
+ data=data,
774
+ remediation=remediation
775
+ or (
776
+ "Reduce context size by: excluding large files, using incremental mode, "
777
+ "or reviewing only specific tasks/phases instead of the full spec."
778
+ ),
779
+ request_id=request_id,
780
+ )
781
+
782
+
783
+ def ai_prompt_not_found_error(
784
+ prompt_id: str,
785
+ *,
786
+ available_prompts: Optional[Sequence[str]] = None,
787
+ workflow: Optional[str] = None,
788
+ remediation: Optional[str] = None,
789
+ request_id: Optional[str] = None,
790
+ ) -> ToolResponse:
791
+ """Create an error response for when a prompt template is not found.
792
+
793
+ Use when a requested prompt ID doesn't exist in the prompt registry.
794
+
795
+ Args:
796
+ prompt_id: The prompt ID that was not found.
797
+ available_prompts: List of valid prompt IDs for the workflow.
798
+ workflow: The workflow context (e.g., "plan_review", "fidelity_review").
799
+ remediation: Guidance on how to find the correct prompt ID.
800
+ request_id: Correlation identifier.
801
+
802
+ Example:
803
+ >>> ai_prompt_not_found_error(
804
+ ... "INVALID_PROMPT",
805
+ ... available_prompts=["PLAN_REVIEW_FULL_V1", "PLAN_REVIEW_QUICK_V1"],
806
+ ... workflow="plan_review",
807
+ ... )
808
+ """
809
+ data: Dict[str, Any] = {"prompt_id": prompt_id}
810
+ if available_prompts:
811
+ data["available_prompts"] = list(available_prompts)
812
+ if workflow:
813
+ data["workflow"] = workflow
814
+
815
+ available_str = ""
816
+ if available_prompts:
817
+ available_str = f" Available: {', '.join(available_prompts[:5])}"
818
+ if len(available_prompts) > 5:
819
+ available_str += f" (and {len(available_prompts) - 5} more)"
820
+
821
+ return error_response(
822
+ f"Prompt '{prompt_id}' not found.{available_str}",
823
+ error_code=ErrorCode.AI_PROMPT_NOT_FOUND,
824
+ error_type=ErrorType.NOT_FOUND,
825
+ data=data,
826
+ remediation=remediation
827
+ or (
828
+ "Use a valid prompt ID from the workflow's prompt builder. "
829
+ "Call list_prompts() to see available templates."
830
+ ),
831
+ request_id=request_id,
832
+ )
833
+
834
+
835
+ def ai_cache_stale_error(
836
+ cache_key: str,
837
+ cache_age_seconds: int,
838
+ max_age_seconds: int,
839
+ *,
840
+ remediation: Optional[str] = None,
841
+ request_id: Optional[str] = None,
842
+ ) -> ToolResponse:
843
+ """Create an error response for when cached AI result is stale.
844
+
845
+ Use when a cached consultation result has expired and needs refresh.
846
+
847
+ Args:
848
+ cache_key: Identifier for the cached item.
849
+ cache_age_seconds: Age of the cached result in seconds.
850
+ max_age_seconds: Maximum allowed age for cached results.
851
+ remediation: Guidance on how to refresh the cache.
852
+ request_id: Correlation identifier.
853
+
854
+ Example:
855
+ >>> ai_cache_stale_error(
856
+ ... "plan_review:spec-001:full",
857
+ ... cache_age_seconds=7200,
858
+ ... max_age_seconds=3600,
859
+ ... )
860
+ """
861
+ return error_response(
862
+ f"Cached result for '{cache_key}' is stale ({cache_age_seconds}s > {max_age_seconds}s)",
863
+ error_code=ErrorCode.AI_CACHE_STALE,
864
+ error_type=ErrorType.AI_PROVIDER,
865
+ data={
866
+ "cache_key": cache_key,
867
+ "cache_age_seconds": cache_age_seconds,
868
+ "max_age_seconds": max_age_seconds,
869
+ },
870
+ remediation=remediation
871
+ or (
872
+ "Re-run the consultation to refresh cached results, "
873
+ "or use --no-cache to bypass the cache."
874
+ ),
875
+ request_id=request_id,
876
+ )
877
+
878
+
879
+ # ---------------------------------------------------------------------------
880
+ # Error Message Sanitization
881
+ # ---------------------------------------------------------------------------
882
+
883
+
884
+ def sanitize_error_message(
885
+ exc: Exception,
886
+ context: str = "",
887
+ include_type: bool = False,
888
+ ) -> str:
889
+ """
890
+ Convert exception to user-safe message without internal details.
891
+
892
+ Logs full exception server-side for debugging per MCP best practices:
893
+ - "Never expose internal details" (07-error-semantics.md:16)
894
+ - "Log full details server-side" (07-error-semantics.md:23)
895
+
896
+ Args:
897
+ exc: The exception to sanitize
898
+ context: Optional context for logging (e.g., "spec validation")
899
+ include_type: Whether to include exception type name in message
900
+
901
+ Returns:
902
+ User-safe error message without file paths, stack traces, or internal state
903
+ """
904
+ # Log full details server-side for debugging
905
+ if context:
906
+ logger.debug(f"Error in {context}: {exc}", exc_info=True)
907
+ else:
908
+ logger.debug(f"Error: {exc}", exc_info=True)
909
+
910
+ # Map known exception types to safe messages
911
+ type_name = type(exc).__name__
912
+
913
+ if isinstance(exc, FileNotFoundError):
914
+ return "Required file or resource not found"
915
+ if isinstance(exc, json.JSONDecodeError):
916
+ return "Invalid JSON format"
917
+ if isinstance(exc, subprocess.TimeoutExpired):
918
+ timeout = getattr(exc, "timeout", "unknown")
919
+ return f"Operation timed out after {timeout} seconds"
920
+ if isinstance(exc, PermissionError):
921
+ return "Permission denied for requested operation"
922
+ if isinstance(exc, ValueError):
923
+ suffix = f" ({type_name})" if include_type else ""
924
+ return f"Invalid value provided{suffix}"
925
+ if isinstance(exc, KeyError):
926
+ return "Required configuration key not found"
927
+ if isinstance(exc, ConnectionError):
928
+ return "Connection failed - service may be unavailable"
929
+ if isinstance(exc, OSError):
930
+ return "System I/O error occurred"
931
+
932
+ # Generic fallback - don't expose exception message
933
+ suffix = f" ({type_name})" if include_type else ""
934
+ return f"An internal error occurred{suffix}"