Orchestrata Ultimate / Specs / 072-tool-search-tool
The ToolSearchTool provides semantic search capabilities across all available tools in the Orchestrata system. It enables users to find relevant tools based on natural language queries, keyword matching, and semantic similarity. The tool maintains a searchable index of tool metadata including names, descriptions, parameters, and usage patterns.
At a glance
| Item |
Value |
| Spec directory |
specs/072-tool-search-tool/ |
| Status line in the spec |
Production Ready |
| Requirement IDs defined |
40 |
With a @traces citation in src/ |
40 (100.0%) |
With a @traces citation in tests/ |
0 (0.0%) |
| Tracked files |
4 |
| RTM page |
072-tool-search-tool |
Reading this spec
This spec defines ToolSearchTool, semantic search across every tool in the Orchestrata system. Users need to find the right tool in a large ecosystem without knowing its exact name, so the tool accepts a natural-language query, keyword matching or fuzzy input and returns ranked results. It keeps a searchable index of tool metadata: names, descriptions, parameters and usage patterns. The method combines embedding-based semantic similarity, keyword matching with TF-IDF weighting, fuzzy matching for typo tolerance and a cached in-memory index.
Five user stories set the scope: finding tools by capability (a query such as "send HTTP requests" returns relevant HTTP tools, with semantic similarity ahead of exact keyword matches and a relevance score on each result), discovering related tools, filtering by tool properties, fuzzy matching for typos, and search history with suggestions. The 40 requirement IDs (REQ-072-NNN) cover core search (a relevance score from 0 to 1, semantic matching with keyword fallback), index management (an in-memory index, updates when tools register or change, rebuild on startup, persistence to disk and incremental updates), caching with a configurable TTL, and performance (95th percentile under 100 ms, concurrent searches and an index of at least 10,000 tools). They also cover faceted search, filtering by category, tags, return type and author, pagination, and a set of named errors such as INVALID_QUERY, INDEX_NOT_READY, INDEX_CORRUPTED, and EMBEDDING_SERVICE_ERROR, which falls back to keyword search.
The implementation is in the search module, with one citation in the tool registry. The requirements traceability matrix lists each ID. The spec's own status line reads Production Ready and it tracks 4 files. Measured coverage is 40 of 40 requirements cited by at least one @traces in src/ (100.0%), spread over 2 modules; the module citing the most of them is orchestrata_ultimate/tools/search (40 requirements). In tests/, 0 requirements are cited by a test-side @traces, so test-side citations are thinner than code-side ones.
Requirements
Checkbox is the state recorded in the requirements checklist; Traced by is the count of src/ symbols whose @traces names the ID.
| ID |
Done |
Requirement |
Traced by |
REQ-072-001 |
no |
The tool SHALL accept a natural language query string and return relevant tools |
6 |
REQ-072-005 |
no |
The tool SHALL return a relevance score (0-1) for each search result |
8 |
REQ-072-008 |
no |
The tool SHALL support semantic similarity matching using embeddings |
5 |
REQ-072-009 |
no |
The tool SHALL support exact keyword matching as fallback |
12 |
REQ-072-011 |
no |
The tool SHALL maintain an in-memory index of all registered tools |
5 |
REQ-072-012 |
no |
The tool SHALL support index updates when tools are registered/updated |
4 |
REQ-072-013 |
no |
The tool SHALL support index rebuild on startup |
5 |
REQ-072-014 |
no |
The tool SHALL persist index state to disk for fast recovery |
3 |
REQ-072-015 |
no |
The tool SHALL support incremental index updates |
2 |
REQ-072-021 |
no |
Search queries SHALL complete within 100ms for 95th percentile |
2 |
REQ-072-022 |
no |
The tool SHALL support concurrent search requests |
4 |
REQ-072-023 |
no |
Index size SHALL support at least 10,000 tools |
1 |
REQ-072-007 |
no |
The tool SHALL support faceted search with category/tag counts |
6 |
REQ-072-003 |
no |
The tool SHALL support filtering by category, tags, return type, and author |
5 |
REQ-072-004 |
no |
The tool SHALL support pagination with limit and offset parameters |
7 |
REQ-072-101 |
no |
INVALID_QUERY — query blank or exceeds max length → 400 validation message |
6 |
REQ-072-102 |
no |
INVALID_FILTER — filter parameter malformed/invalid → 400 field error |
4 |
REQ-072-103 |
no |
INVALID_PAGINATION — limit/offset out of range → 400 valid range |
3 |
REQ-072-104 |
no |
INDEX_NOT_READY — search index not initialized → 503 retry-after |
3 |
REQ-072-105 |
no |
INDEX_CORRUPTED — index data corrupted → 500, trigger rebuild |
2 |
REQ-072-106 |
no |
TOOL_NOT_FOUND — referenced tool does not exist → 404 |
1 |
REQ-072-107 |
no |
CACHE_ERROR — cache operation failed → log, continue without cache |
2 |
REQ-072-108 |
no |
EMBEDDING_SERVICE_ERROR — embedding service unavailable → fall back to keyword search |
4 |
REQ-072-109 |
no |
RATE_LIMIT_EXCEEDED — too many search requests → 429 retry-after (governance seam) |
1 |
REQ-072-110 |
no |
PERMISSION_DENIED — user lacks search permission → 403 (governance seam) |
1 |
REQ-072-111 |
no |
INVALID_SORT_OPTION — sort parameter not recognized → 400 valid options |
5 |
REQ-072-112 |
no |
TIMEOUT — search timed out → 504 with partial results if available |
2 |
REQ-072-201 |
no |
SHALL sanitize all query inputs to prevent injection attacks |
2 |
REQ-072-202 |
no |
SHALL validate query length (max 500 characters) |
2 |
REQ-072-203 |
no |
SHALL escape special characters in search queries |
2 |
REQ-072-204 |
no |
SHALL validate all filter parameters against allowed values |
2 |
REQ-072-002 |
no |
The tool SHALL support fuzzy matching for typos in queries |
7 |
REQ-072-010 |
no |
The tool SHALL support compound queries with AND/OR operators |
4 |
REQ-072-024 |
no |
Search SHALL support wildcard prefixes (e.g., "http*") |
11 |
REQ-072-006 |
no |
The tool SHALL provide search suggestions based on partial input |
6 |
REQ-072-016 |
no |
The tool SHALL cache search results with configurable TTL |
3 |
REQ-072-017 |
no |
The tool SHALL invalidate cache entries when tools are updated |
3 |
REQ-072-018 |
no |
The tool SHALL support cache invalidation by tool_id |
2 |
REQ-072-019 |
no |
The tool SHALL support cache warming on startup |
4 |
REQ-072-020 |
no |
The tool SHALL support cache statistics reporting |
2 |
Code that traces this spec
Checklists
checklists/requirements.md
The requirement list above comes from this file; 0 of 40 checkbox items are ticked.
Other tracked files
specs/072-tool-search-tool/compliance-audit.md
specs/072-tool-search-tool/requirements.md
Full spec text
Verbatim from specs/072-tool-search-tool/spec.md; headings are pushed down two levels.
- Spec ID: 072-tool-search-tool
- Title: ToolSearchTool - Semantic Search Across Tools
- Author: Mohamed
- Status: Production Ready
- Created: 2024-01-15
- Last Updated: 2024-06-20
- Priority: P1
- Version: 1.0.0
- Extends: None
Overview
The ToolSearchTool provides semantic search capabilities across all available tools in the Orchestrata system. It enables users to find relevant tools based on natural language queries, keyword matching, and semantic similarity. The tool maintains a searchable index of tool metadata including names, descriptions, parameters, and usage patterns.
Why: Users need to discover and locate appropriate tools within a large ecosystem without knowing exact tool names or commands.
How: The tool uses embedding-based semantic similarity, keyword matching with TF-IDF weighting, fuzzy matching for typo tolerance, and a cached in-memory index for fast retrieval.
User Scenarios
- As a system user
- I want to search for tools using natural language queries like "send HTTP requests" or "make API calls"
- So that I can discover relevant tools without knowing their exact names
Acceptance Criteria:
- [ ] Query "send HTTP requests" returns HttpClient, FetchTool, ApiRequestTool
- [ ] Semantic similarity takes precedence over exact keyword matches
- [ ] Results include relevance scores
- As a data processing engineer
- I want to find all tools related to "JSON parsing"
- So that I can identify all available options for working with JSON data
Acceptance Criteria:
- [ ] Search returns JsonParser, JsonValidator, JsonFormatter
- [ ] Related tools with JSON functionality in descriptions are included
- [ ] Faceted results show category distribution
- As a developer
- I want to filter search results by category, return type, and required parameters
- So that I can narrow down to tools that match my specific requirements
Acceptance Criteria:
- [ ] Combined filters (category + return_type) work correctly
- [ ] Filtered results maintain relevance ranking
- [ ] Blank filter combinations return appropriate error message
US-004: Fuzzy Matching for Typos
- As a user with keyboard input errors
- I want to find tools even with typos in my query
- So that I can still discover tools despite spelling mistakes
Acceptance Criteria:
- [ ] Query "reacieve" returns ReceiveMessageTool
- [ ] Fuzzy threshold is configurable
- [ ] Results indicate fuzzy match was applied
US-005: Search History and Suggestions
- As a frequent user
- I want to receive search suggestions based on my history and popular searches
- So that I can quickly access previously found tools
Acceptance Criteria:
- [ ] Suggestions appear after 3+ historical queries
- [ ] Popular searches within organization are included
- [ ] Suggestions update in real-time
Terminology
| Term |
Definition |
| Tool Index |
In-memory searchable store of all tool metadata |
| Semantic Search |
Search using embedding-based similarity rather than exact matches |
| Fuzzy Matching |
Technique for matching strings with minor spelling differences |
| TF-IDF |
Term Frequency-Inverse Document Frequency weighting algorithm |
| Relevance Score |
Numeric value (0-1) indicating match quality |
| Faceted Search |
Search results grouped by categories with counts |
| Cache Warming |
Pre-populating cache with expected queries on startup |
| LRU |
Least Recently Used eviction policy for cache management |
Data Models
4.1 Tool Index Entry
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "ToolIndexEntry",
"type": "object",
"properties": {
"tool_id": {
"type": "string",
"pattern": "^[a-zA-Z0-9_-]{1,64}$",
"description": "Unique identifier for the tool"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 128,
"description": "Human-readable tool name"
},
"description": {
"type": "string",
"maxLength": 4096,
"description": "Detailed description of tool functionality"
},
"category": {
"type": "string",
"enum": [
"network",
"data_processing",
"file_system",
"security",
"database",
"communication",
"analytics",
"integration",
"utility",
"custom"
]
},
"tags": {
"type": "array",
"items": {
"type": "string",
"maxLength": 32
},
"maxItems": 20
},
"parameters": {
"type": "array",
"items": {
"$ref": "#/definitions/ParameterDefinition"
}
},
"return_type": {
"type": "string",
"enum": ["string", "number", "boolean", "object", "array", "binary", "stream", "void"]
},
"version": {
"type": "string",
"pattern": "^\\d+\\.\\d+\\.\\d+$"
},
"author": {
"type": "string",
"maxLength": 128
},
"created_at": {
"type": "string",
"format": "date-time"
},
"updated_at": {
"type": "string",
"format": "date-time"
},
"usage_count": {
"type": "integer",
"minimum": 0
},
"success_rate": {
"type": "number",
"minimum": 0,
"maximum": 1
}
},
"required": ["tool_id", "name", "description", "category"],
"definitions": {
"ParameterDefinition": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"type": {
"type": "string"
},
"required": {
"type": "boolean"
},
"description": {
"type": "string"
},
"default": {}
},
"required": ["name", "type"]
}
}
}
Search Request
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "ToolSearchRequest",
"type": "object",
"properties": {
"query": {
"type": "string",
"minLength": 1,
"maxLength": 500,
"description": "Search query string"
},
"filters": {
"$ref": "#/definitions/SearchFilters"
},
"options": {
"$ref": "#/definitions/SearchOptions"
}
},
"required": ["query"],
"definitions": {
"SearchFilters": {
"type": "object",
"properties": {
"categories": {
"type": "array",
"items": {
"type": "string"
}
},
"tags": {
"type": "array",
"items": {
"type": "string"
}
},
"return_types": {
"type": "array",
"items": {
"type": "string",
"enum": ["string", "number", "boolean", "object", "array", "binary", "stream", "void"]
}
},
"min_success_rate": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"authors": {
"type": "array",
"items": {
"type": "string"
}
},
"date_range": {
"$ref": "#/definitions/DateRange"
}
}
},
"SearchOptions": {
"type": "object",
"properties": {
"limit": {
"type": "integer",
"minimum": 1,
"maximum": 100,
"default": 10
},
"offset": {
"type": "integer",
"minimum": 0,
"default": 0
},
"fuzzy_threshold": {
"type": "number",
"minimum": 0,
"maximum": 1,
"default": 0.7
},
"include_disabled": {
"type": "boolean",
"default": false
},
"rank_by": {
"type": "string",
"enum": ["relevance", "popularity", "recency", "success_rate"],
"default": "relevance"
}
}
},
"DateRange": {
"type": "object",
"properties": {
"start": {
"type": "string",
"format": "date-time"
},
"end": {
"type": "string",
"format": "date-time"
}
}
}
}
}
Search Response
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "ToolSearchResponse",
"type": "object",
"properties": {
"results": {
"type": "array",
"items": {
"$ref": "#/definitions/SearchResult"
}
},
"total_count": {
"type": "integer"
},
"query": {
"type": "string"
},
"pagination": {
"$ref": "#/definitions/PaginationInfo"
},
"suggestions": {
"type": "array",
"items": {
"type": "string"
}
},
"facets": {
"$ref": "#/definitions/SearchFacets"
}
},
"definitions": {
"SearchResult": {
"type": "object",
"properties": {
"tool": {
"$ref": "ToolIndexEntry"
},
"score": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"matched_fields": {
"type": "array",
"items": {
"type": "string"
}
},
"highlight": {
"type": "string"
}
}
},
"PaginationInfo": {
"type": "object",
"properties": {
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"has_more": {
"type": "boolean"
}
}
},
"SearchFacets": {
"type": "object",
"properties": {
"categories": {
"type": "array",
"items": {
"$ref": "#/definitions/FacetCount"
}
},
"tags": {
"type": "array",
"items": {
"$ref": "#/definitions/FacetCount"
}
},
"return_types": {
"type": "array",
"items": {
"$ref": "#/definitions/FacetCount"
}
}
}
},
"FacetCount": {
"type": "object",
"properties": {
"value": {
"type": "string"
},
"count": {
"type": "integer"
}
}
}
}
}
Functional Requirements
Core Search Capabilities
| ID |
Requirement |
Priority |
| FR-001 |
The tool SHALL accept a natural language query string and return relevant tools |
MUST |
| FR-002 |
The tool SHALL support fuzzy matching for typos in queries |
MUST |
| FR-003 |
The tool SHALL support filtering by category, tags, return type, and author |
MUST |
| FR-004 |
The tool SHALL support pagination with limit and offset parameters |
MUST |
| FR-005 |
The tool SHALL return a relevance score (0-1) for each search result |
MUST |
| FR-006 |
The tool SHALL provide search suggestions based on partial input |
SHOULD |
| FR-007 |
The tool SHALL support faceted search with category/tag counts |
SHOULD |
| FR-008 |
The tool SHALL support semantic similarity matching using embeddings |
MUST |
| FR-009 |
The tool SHALL support exact keyword matching as fallback |
MUST |
| FR-010 |
The tool SHALL support compound queries with AND/OR operators |
SHOULD |
Index Management
| ID |
Requirement |
Priority |
| FR-011 |
The tool SHALL maintain an in-memory index of all registered tools |
MUST |
| FR-012 |
The tool SHALL support index updates when tools are registered/updated |
MUST |
| FR-013 |
The tool SHALL support index rebuild on startup |
MUST |
| FR-014 |
The tool SHALL persist index state to disk for fast recovery |
SHOULD |
| FR-015 |
The tool SHALL support incremental index updates |
SHOULD |
Caching
| ID |
Requirement |
Priority |
| FR-016 |
The tool SHALL cache search results with configurable TTL |
MUST |
| FR-017 |
The tool SHALL invalidate cache entries when tools are updated |
MUST |
| FR-018 |
The tool SHALL support cache invalidation by tool_id |
MUST |
| FR-019 |
The tool SHALL support cache warming on startup |
SHOULD |
| FR-020 |
The tool SHALL support cache statistics reporting |
SHOULD |
| ID |
Requirement |
Priority |
| FR-021 |
Search queries SHALL complete within 100ms for 95th percentile |
MUST |
| FR-022 |
The tool SHALL support concurrent search requests |
MUST |
| FR-023 |
Index size SHALL support at least 10,000 tools |
MUST |
| FR-024 |
Search SHALL support wildcard prefixes (e.g., "http*") |
SHOULD |
Error Conditions
| ID |
Error Code |
Description |
Handling |
| ERR-001 |
INVALID_QUERY |
Query string is blank or exceeds maximum length |
Return 400 with validation message |
| ERR-002 |
INVALID_FILTER |
Filter parameter is malformed or invalid |
Return 400 with specific field error |
| ERR-003 |
INVALID_PAGINATION |
Limit or offset is out of range |
Return 400 with valid range |
| ERR-004 |
INDEX_NOT_READY |
Search index is not initialized |
Return 503 with retry-after header |
| ERR-005 |
INDEX_CORRUPTED |
Index data is corrupted |
Return 500, trigger rebuild |
| ERR-006 |
TOOL_NOT_FOUND |
Referenced tool does not exist |
Return 404 for lookup operations |
| ERR-007 |
CACHE_ERROR |
Cache operation failed |
Log error, continue without cache |
| ERR-008 |
EMBEDDING_SERVICE_ERROR |
External embedding service unavailable |
Fall back to keyword search |
| ERR-009 |
RATE_LIMIT_EXCEEDED |
Too many search requests |
Return 429 with retry-after |
| ERR-010 |
PERMISSION_DENIED |
User lacks permission to search |
Return 403 with reason |
| ERR-011 |
INVALID_SORT_OPTION |
Sort parameter is not recognized |
Return 400 with valid options |
| ERR-012 |
TIMEOUT |
Search operation timed out |
Return 504 with partial results if available |
API Contracts
Search Endpoint
POST /api/v1/tools/search
Content-Type: application/json
Authorization: Bearer <token>
X-Request-ID: <uuid>
Request Body
{
"query": "HTTP client for REST APIs",
"filters": {
"categories": ["network"],
"return_types": ["object"]
},
"options": {
"limit": 10,
"offset": 0,
"rank_by": "relevance"
}
}
Success Response (200)
{
"results": [
{
"tool": {
"tool_id": "http_client_v2",
"name": "HTTP Client",
"description": "Advanced HTTP client with retry logic and timeout support",
"category": "network",
"tags": ["http", "rest", "api", "client"],
"parameters": [...],
"return_type": "object",
"version": "2.1.0",
"author": "platform-team",
"created_at": "2024-01-15T10:00:00Z",
"updated_at": "2024-06-20T14:30:00Z",
"usage_count": 15420,
"success_rate": 0.987
},
"score": 0.95,
"matched_fields": ["name", "description", "tags"],
"highlight": "Advanced <em>HTTP</em> <em>client</em> with retry logic"
}
],
"total_count": 5,
"query": "HTTP client for REST APIs",
"pagination": {
"limit": 10,
"offset": 0,
"has_more": false
},
"suggestions": ["http request", "rest client"],
"facets": {
"categories": [{"value": "network", "count": 5}],
"tags": [{"value": "http", "count": 4}, {"value": "rest", "count": 3}],
"return_types": [{"value": "object", "count": 3}]
}
}
Index Management Endpoints
POST /api/v1/tools/index/rebuild - Rebuild the entire search index
POST /api/v1/tools/index/update - Update index with new/modified tool
DELETE /api/v1/tools/index/tool/{tool_id} - Remove tool from index
GET /api/v1/tools/index/stats - Get index statistics
Cache Management Endpoints
DELETE /api/v1/tools/search/cache - Clear all cached results
DELETE /api/v1/tools/search/cache/{tool_id} - Invalidate cache for specific tool
GET /api/v1/tools/search/cache/stats - Get cache statistics
Non-Functional Requirements
| Metric |
Target |
Measurement |
| Search Latency (P95) |
≤ 100ms |
10,000 tool index |
| Search Latency (P99) |
≤ 200ms |
10,000 tool index |
| Index Build Time |
≤ 30s |
10,000 tools |
| Concurrent Searches |
≥ 50 requests |
Simultaneous queries |
| Memory Usage |
≤ 500MB |
10,000 tool index |
| Cache Hit Ratio |
≥ 80% |
After warmup |
| Cache Latency Reduction |
≥ 50% |
Compared to uncached |
Scalability Requirements
- Horizontal Scaling: Support multiple search instances with shared cache
- Index Sharding: Partition index by category for faster filtering
- Embedding Storage: Efficient storage for 768-dimension embeddings
- Cache Distribution: Redis cluster support for distributed caching
- Rate Limiting: 100 requests/minute per user, configurable per user group
Availability Requirements
- Uptime: 99.9% availability (SLA)
- Graceful Degradation: Continue with keyword search if embeddings unavailable
- Recovery Time: Index rebuild within 30 seconds of corruption detection
- Cache Persistence: Survive restart with persisted cache data
Reliability Requirements
- Data Consistency: Index synchronized with tool registry
- Cache Coherence: Invalidations propagate within 100ms
- Search Accuracy: >90% user satisfaction in relevance testing
- Zero Data Loss: Persistent index prevents data loss on restart
Security Requirements
Authentication and Authorization
| ID |
Requirement |
Priority |
| SR-001 |
SHALL require valid authentication token for all search requests |
MUST |
| SR-002 |
SHALL enforce user permissions based on tool access levels |
MUST |
| SR-003 |
SHALL validate JWT tokens with proper signature verification |
MUST |
| SR-004 |
SHALL reject requests with expired tokens |
MUST |
| SR-005 |
SHALL support API key authentication as fallback |
SHOULD |
| SR-006 |
SHALL implement OAuth 2.0 client credentials flow |
SHOULD |
| ID |
Requirement |
Priority |
| SR-007 |
SHALL sanitize all query inputs to prevent injection attacks |
MUST |
| SR-008 |
SHALL validate query length (max 500 characters) |
MUST |
| SR-009 |
SHALL escape special characters in search queries |
MUST |
| SR-010 |
SHALL validate all filter parameters against allowed values |
MUST |
| SR-011 |
SHALL reject queries containing malicious patterns |
MUST |
| SR-012 |
SHALL limit wildcard usage to prevent resource exhaustion |
MUST |
Data Protection
| ID |
Requirement |
Priority |
| SR-013 |
SHALL encrypt sensitive data at rest using AES-256 |
MUST |
| SR-014 |
SHALL use TLS 1.3 for all network communications |
MUST |
| SR-015 |
SHALL implement field-level encryption for PII in search logs |
MUST |
| SR-016 |
SHALL hash user identifiers in analytics data |
MUST |
| SR-017 |
SHALL comply with GDPR data retention policies |
MUST |
| SR-018 |
SHALL implement secure key management for encryption keys |
MUST |
Rate Limiting and DDoS Protection
| ID |
Requirement |
Priority |
| SR-019 |
SHALL implement rate limiting: 100 requests/minute per user |
MUST |
| SR-020 |
SHALL support configurable rate limits per user group |
MUST |
| SR-021 |
SHALL return 429 status with retry-after header on limit breach |
MUST |
| SR-022 |
SHALL implement circuit breaker pattern for external dependencies |
MUST |
| SR-023 |
SHALL detect and block suspicious request patterns |
SHOULD |
| SR-024 |
SHALL implement request size limits (max 10KB per request) |
MUST |
Audit and Monitoring
| ID |
Requirement |
Priority |
| SR-025 |
SHALL log all search queries with user ID and timestamp |
MUST |
| SR-026 |
SHALL implement tamper-evident audit logs |
MUST |
| SR-027 |
SHALL monitor for security events and trigger alerts |
MUST |
| SR-028 |
SHALL maintain audit logs for minimum 90 days |
MUST |
| SR-029 |
SHALL track failed authentication attempts |
MUST |
| SR-030 |
SHALL implement real-time security monitoring dashboard |
SHOULD |
Secure Configuration
| ID |
Requirement |
Priority |
| SR-031 |
SHALL store secrets in secure vault (not in code or config files) |
MUST |
| SR-032 |
SHALL require rotation of API keys every 90 days |
MUST |
| SR-033 |
SHALL disable directory listing and default credentials |
MUST |
| SR-034 |
SHALL implement secure defaults for all configuration options |
MUST |
| SR-035 |
SHALL validate configuration on startup |
MUST |
| SR-036 |
SHALL support environment-specific security policies |
SHOULD |
Security Testing
| ID |
Requirement |
Priority |
| SR-037 |
SHALL conduct quarterly penetration testing |
MUST |
| SR-038 |
SHALL perform static code analysis for security vulnerabilities |
MUST |
| SR-039 |
SHALL implement automated security scanning in CI/CD |
MUST |
| SR-040 |
SHALL conduct dependency vulnerability scanning |
MUST |
| SR-041 |
SHALL perform security review before major releases |
MUST |
| SR-042 |
SHALL maintain security incident response plan |
SHOULD |
Compliance Requirements
| ID |
Requirement |
Priority |
| SR-043 |
SHALL comply with SOC 2 Type II requirements |
MUST |
| SR-044 |
SHALL implement data classification and handling policies |
MUST |
| SR-045 |
SHALL maintain compliance with applicable privacy laws |
MUST |
| SR-046 |
SHALL provide data subject rights support (access, deletion) |
MUST |
| SR-047 |
SHALL implement data minimization principles |
MUST |
| SR-048 |
SHALL maintain security documentation and procedures |
MUST |
Technical Design
System Architecture
┌─────────────────────────────────────────────────────────────┐
│ Client Application │
└──────────────────────────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Load Balancer │
└──────────────────────────┬──────────────────────────────────┘
│
┌──────────────┴──────────────┐
▼ ▼
┌────────────────────┐ ┌────────────────────┐
│ Search API │ │ Search API │
│ Instance 1 │ │ Instance 2 │
└──────────┬─────────┘ └──────────┬─────────┘
│ │
▼ ▼
┌─────────────────────────────────────────────────────────────┐
│ In-Memory Index │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Category │ │ Embeddings │ │ Tool ID │ │
│ │ Partition │ │ Cache │ │ Index │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└──────────────────────────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Redis Cache Cluster │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Search │ │ Embedding │ │ Query │ │
│ │ Results │ │ Cache │ │ History │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
Search Pipeline
- Query Processing: Input validation, query parsing, partial query handling
- Index Lookup: Category filtering, candidate retrieval, embedding lookup
- Ranking Computation: Semantic similarity, TF-IDF scoring, popularity weighting
- Result Assembly: Sorting, pagination, highlighting, facet calculation
- Caching: Cache key generation, result storage with TTL, LRU eviction
Index Management
- Build Process: Tool retrieval, embedding generation, TF-IDF vocabulary, category partitioning, disk persistence
- Update Process: Change notification, embedding update, index update, cache invalidation
Caching Strategy
- Cache Keys: Hash of query + normalized filters + options
- TTL: 5 minutes default, configurable
- Invalidation: Tool updates, index rebuild, manual invalidation
- Statistics: Hit/miss ratio, latency comparison, memory usage
Examples
Basic Search
Request:
POST /api/v1/tools/search
{
"query": "HTTP client"
}
Response:
{
"results": [
{
"tool": {
"tool_id": "http_client_v2",
"name": "HTTP Client",
"description": "Advanced HTTP client with retry logic",
"category": "network",
"tags": ["http", "client", "rest"],
"version": "2.1.0"
},
"score": 0.95,
"matched_fields": ["name", "description", "tags"]
}
],
"total_count": 1,
"query": "HTTP client"
}
Filtered Search
Request:
POST /api/v1/tools/search
{
"query": "parse data",
"filters": {
"categories": ["data_processing"],
"return_types": ["object"]
},
"options": {
"limit": 5
}
}
Paginated Search
Request:
POST /api/v1/tools/search
{
"query": "database",
"options": {
"limit": 10,
"offset": 20,
"rank_by": "popularity"
}
}
Security
Search Ranking Algorithm
The search ranking algorithm combines multiple signals:
- Semantic Similarity (40%): Embedding-based similarity between query and tool description
- Keyword Match Score (25%): TF-IDF weighted keyword matching
- Popularity Factor (15%): Normalized usage count
- Success Rate (10%): Tool success rate as quality indicator
- Recency Bonus (10%): Recently updated tools get a boost
final_score = (0.40 * semantic_score) +
(0.25 * keyword_score) +
(0.15 * popularity_score) +
(0.10 * success_rate_score) +
(0.10 * recency_score)
Indexing Strategy
- Initial Index: Built from tool registry on startup
- Incremental Updates: New tools added to index within 100ms
- Index Partitioning: Tools partitioned by category for faster filtering
- Embedding Storage: Pre-computed embeddings stored with index entries
- Deduplication: Duplicate entries prevented via tool_id uniqueness constraint
Cache Invalidation
| Event |
Invalidation Strategy |
| Tool Updated |
Invalidate all cached searches containing tool_id |
| Tool Deleted |
Invalidate all cached searches |
| Index Rebuilt |
Clear entire cache |
| TTL Expiry |
Time-based expiration (default: 5 minutes) |
| Cache Size Limit |
LRU eviction when cache exceeds 1000 entries |
Access Control
- Search queries require valid authentication token
- Rate limiting: 100 requests per minute per user
- Results filtered by user's tool access permissions
- Audit logging for all search queries
- Input validation prevents injection attacks
- Query logs sanitized to remove sensitive data
Data Privacy
- Search queries not persisted by default
- User search history stored separately with opt-in consent
- Analytics data anonymized
- Embeddings generated without user-identifying information
- Cache entries expire automatically
Governance
Ownership
| Role |
Responsibility |
| Spec Owner |
Mohamed (Principal Python Engineer) |
| Technical Lead |
Architecture team |
| API Owner |
Platform team |
| Security Owner |
Security team |
| Operations Owner |
SRE team |
Change Management
- Minor Changes: Team lead approval, version bump (X.Y)
- Major Changes: Architecture review board, version bump (X.0)
- Emergency Fixes: Can deploy immediately with post-hoc review
- Rollback: Automated rollback on error rate threshold breach
Deprecation Policy
- Announcement: 90 days before deprecation
- Compatibility: Maintained for 1 year minimum
- Migration Guide: Provided for major versions
- Sunset Date: Clearly communicated in API responses
Compliance
- Audit: Monthly review of search logs and access patterns
- Privacy: GDPR compliant query handling
- Security: Quarterly security assessment
- Performance: Weekly performance report
Dependencies
Production Dependencies
| Package |
Version |
Purpose |
| numpy |
^1.24.0 |
Numerical operations for embeddings |
| sentence-transformers |
^2.2.0 |
Semantic embeddings generation |
| redis |
^5.0.0 |
Distributed caching layer |
| pydantic |
^2.0.0 |
Data validation |
| fastapi |
^0.104.0 |
HTTP server |
| uvicorn |
^0.24.0 |
ASGI server |
Development Dependencies
| Package |
Version |
Purpose |
| pytest |
^7.4.0 |
Testing framework |
| pytest-asyncio |
^0.21.0 |
Async test support |
| httpx |
^0.25.0 |
HTTP client for tests |
| pytest-cov |
^4.1.0 |
Coverage reporting |
External Services
| Service |
Purpose |
SLA |
Fallback |
| Embedding Service |
Generate tool embeddings |
99.9% |
Keyword-only search |
| Redis Cluster |
Distributed caching |
99.9% |
In-memory cache |
| Tool Registry |
Source of truth for tools |
99.9% |
Last known good index |
Testing Requirements
Unit Tests
| Test ID |
Description |
| UT-001 |
Test search with valid query returns results |
| UT-002 |
Test search with blank query returns error |
| UT-003 |
Test fuzzy matching handles typos |
| UT-004 |
Test category filtering works correctly |
| UT-005 |
Test pagination returns correct results |
| UT-006 |
Test ranking algorithm produces expected scores |
| UT-007 |
Test cache stores and retrieves results |
| UT-008 |
Test cache invalidation on tool update |
| UT-009 |
Test index rebuild populates all tools |
| UT-010 |
Test error handling for invalid filters |
| UT-011 |
Test semantic similarity calculation |
| UT-012 |
Test TF-IDF scoring |
Integration Tests
| Test ID |
Description |
| IT-001 |
End-to-end search flow with real embeddings |
| IT-002 |
Concurrent search requests handle correctly |
| IT-003 |
Cache warming on startup works |
| IT-004 |
Rate limiting triggers correctly |
| IT-005 |
Index recovery after corruption |
| IT-006 |
Multiple filter combinations work correctly |
| IT-007 |
Search suggestions appear based on history |
| IT-008 |
Faceted search returns correct counts |
| Test ID |
Description |
| PT-001 |
Search latency under 100ms for 10k tools |
| PT-002 |
Support 50 concurrent searches |
| PT-003 |
Index rebuild completes in under 30 seconds |
| PT-004 |
Memory usage under 500MB for 10k tools |
| PT-005 |
Cache hit ratio exceeds 80% |
| PT-006 |
Load test with 1000 queries/second |
Test Coverage Targets
- Line Coverage: ≥ 90%
- Branch Coverage: ≥ 85%
- Function Coverage: ≥ 95%
- Critical Path Coverage: 100%
Integration Points
- Connection: REST API to tool registry service
- Protocol: HTTP/HTTPS with authentication
- Data Flow: Pull-based synchronization
- Update Mechanism: Webhook notifications on tool changes
- Failure Handling: Retry with exponential backoff
- Data Format: JSON with schema validation
Embedding Service Integration
- Connection: gRPC to embedding service
- Protocol: Protocol Buffers over HTTP/2
- Data Flow: Synchronous generation per tool
- Update Mechanism: Batch embedding generation
- Failure Handling: Graceful degradation to keyword-only
- Model Version: Configurable embedding model
Redis Cache Integration
- Connection: Redis Cluster with client-side sharding
- Protocol: RESP (Redis Serialization Protocol)
- Data Flow: Direct client connection with connection pooling
- Update Mechanism: Cache-aside pattern
- Failure Handling: Continue without cache, log degradation
- Data Format: Serialized search results with TTL
Monitoring Integration
- Metrics: Prometheus metrics endpoint
- Logging: Structured logs to central logging service
- Tracing: OpenTelemetry distributed tracing
- Alerting: PagerDuty integration for critical issues
- Dashboard: Grafana dashboards for performance metrics
User Feedback Integration
- Feedback Collection: API endpoint for search result feedback
- Analytics: Anonymous usage analytics
- A/B Testing: Framework for testing ranking improvements
- Quality Metrics: Automated relevance scoring
Success Criteria
- [ ] Search returns relevant results within 100ms for 95% of queries
- [ ] Fuzzy matching corrects up to 2 character substitutions
- [ ] All filters (category, tags, return_type) work correctly in combination
- [ ] Pagination returns correct result subsets
- [ ] Cache reduces average latency by at least 50%
- [ ] Cache invalidation occurs within 100ms of tool update
- [ ] Index rebuild completes for 10,000 tools in under 30 seconds
- [ ] All error conditions return appropriate HTTP status codes
- [ ] Search results include relevance scores
- [ ] All unit tests pass with >90% coverage
- [ ] Semantic search provides better relevance than keyword-only (user study)
- [ ] System handles 1000 searches/second at P95 latency target
- [ ] Cache hit ratio exceeds 80% in production
- [ ] Zero data loss during normal operations
- [ ] Graceful degradation when embedding service unavailable
- [ ] All 12 error conditions tested and documented
- [ ] Search suggestions improve user efficiency by 25%
- [ ] Integration tests pass with real external dependencies
- [ ] Security audit passes with no critical findings
- [ ] Performance tests meet all P95 and P99 targets
Observability
Logging Requirements
- Component Logging
- Log all major operations with appropriate log levels
- Include correlation IDs for request tracing
- Log performance metrics for critical operations
- Log errors with full context for debugging
Metrics Requirements
- Performance Metrics
- Operation duration histograms
- Request/error rate counters
- Resource utilization gauges
- Business metrics relevant to domain
Tracing Requirements
- Distributed Tracing
- Trace propagation across component boundaries
- Span attributes for domain-specific context
- Trace sampling based on operational needs
Alerting Requirements
- Critical Alerts
- Error rate spikes
- Performance degradation
- Resource exhaustion
- Business metric anomalies
Dashboard Requirements
- Operational Dashboard
- Real-time system health
- Performance trends
- Error analysis
- Resource monitoring
Revision History
| Version |
Date |
Author |
Changes |
| 1.0.0 |
2024-06-20 |
Mohamed |
Initial production release with semantic search, caching, and full feature set |
| 0.9.0 |
2024-05-15 |
Mohamed |
Added governance section, integration points, and expanded non-functional requirements |
| 0.8.0 |
2024-04-20 |
Mohamed |
Added technical design section, examples, and security enhancements |
| 0.7.0 |
2024-03-10 |
Mohamed |
Converted from EC-001 to ERR-001 error codes, updated user scenarios format |
| 0.6.0 |
2024-02-15 |
Mohamed |
Added metadata section and reorganized to match SPEC_STANDARD |
| 0.5.0 |
2024-01-30 |
Mohamed |
First complete draft with functional requirements and API contracts |
| 0.1.0 |
2024-01-15 |
Mohamed |
Initial specification created |