STATEDIAGRAM.md
May 18, 2026 Β· View on GitHub
π European Parliament MCP Server β State Diagrams
System State Transitions and Lifecycle Management
Complete state machine documentation for server, tools, cache, and rate limiter
π Document Owner: Hack23 | π Version: 1.2 | π Last Updated: 2026-04-21 (UTC) π Review Cycle: Quarterly | β° Next Review: 2026-07-21 π·οΈ Classification: Public (Open Source MCP Server) β ISMS Compliance: ISO 27001 (A.5.1, A.8.1, A.14.2), NIST CSF 2.0 (ID.AM, PR.DS), CIS Controls v8.1 (2.1, 16.1)
π Table of Contents
- Security Documentation Map
- Server Lifecycle States
- Tool Execution States
- API Connection States
- Cache Entry States
- Rate Limiter States
- DI Container States
- Data Availability States
πΊοΈ Security Documentation Map
| Document | Current | Future | Description |
|---|---|---|---|
| Architecture | ARCHITECTURE.md | FUTURE_ARCHITECTURE.md | C4 model, containers, components, ADRs |
| Security Architecture | SECURITY_ARCHITECTURE.md | FUTURE_SECURITY_ARCHITECTURE.md | Security controls, threat model |
| Data Model | DATA_MODEL.md | FUTURE_DATA_MODEL.md | Entity relationships, branded types |
| Flowchart | FLOWCHART.md | FUTURE_FLOWCHART.md | Business process flows |
| State Diagram | STATEDIAGRAM.md | FUTURE_STATEDIAGRAM.md | System state transitions |
| Mind Map | MINDMAP.md | FUTURE_MINDMAP.md | System concepts and relationships |
| SWOT Analysis | SWOT.md | FUTURE_SWOT.md | Strategic positioning |
| Threat Model | THREAT_MODEL.md | FUTURE_THREAT_MODEL.md | STRIDE, MITRE ATT&CK, attack trees |
| CRA Assessment | CRA-ASSESSMENT.md | β | EU Cyber Resilience Act conformity |
π₯οΈ Server Lifecycle States
stateDiagram-v2
[*] --> Initializing : Process started
Initializing --> DISetup : Environment loaded
DISetup --> ClientsReady : DI container built
ClientsReady --> ToolsRegistered : 62 tools registered
ToolsRegistered --> ResourcesRegistered : 9 resources registered
ResourcesRegistered --> PromptsRegistered : 7 prompts registered
PromptsRegistered --> Running : MCP stdio listener started
Running --> Processing : Tool call received
Processing --> Running : Tool call completed
Running --> Degraded : EP API unavailable
Degraded --> Running : EP API recovered
Running --> ShuttingDown : SIGTERM / SIGINT received
Degraded --> ShuttingDown : SIGTERM / SIGINT received
Processing --> ShuttingDown : Fatal error
ShuttingDown --> Stopped : Cleanup complete
Stopped --> [*]
note right of Running
Nominal operating state.
Accepting MCP tool calls
via stdio transport.
end note
note right of Degraded
EP API unreachable.
Cache-only mode active.
Returning stale data
or errors to clients.
end note
π§ Tool Execution States
stateDiagram-v2
[*] --> Received : MCP tool_call arrives
Received --> Routing : Tool name lookup
Routing --> NotFound : Tool not registered
Routing --> Validating : Tool found
NotFound --> [*] : Return error to client
Validating --> ValidationFailed : Zod parse error
Validating --> RateLimitCheck : Input valid
ValidationFailed --> [*] : Return validation error
RateLimitCheck --> RateLimited : No token available
RateLimitCheck --> AuditLogging : Token granted
RateLimited --> [*] : Return rate limit error
AuditLogging --> CacheCheck : Invocation logged
CacheCheck --> CacheHit : Entry found and fresh
CacheCheck --> FetchingAPI : Cache miss
CacheHit --> Returning : Cache data retrieved
FetchingAPI --> APIError : HTTP error / timeout
FetchingAPI --> Parsing : HTTP 200 received
APIError --> Retrying : Retry count < 3
APIError --> ErrorReturn : Retry count >= 3
Retrying --> FetchingAPI : After backoff
Parsing --> ParseError : JSON-LD parse failure
Parsing --> Validating2 : Parse success
ParseError --> ErrorReturn : Log and return error
Validating2 --> Caching : Response validated
Caching --> Returning : Stored in LRU cache
Returning --> MetricsUpdate : Result prepared
ErrorReturn --> MetricsUpdate : Error prepared
MetricsUpdate --> [*] : Response sent to client
π API Connection States
stateDiagram-v2
[*] --> Unknown : Client initialized
Unknown --> Checking : Health check triggered
Checking --> Available : Ping success (200)
Checking --> Unavailable : Ping failed / timeout
Available --> Requesting : API call initiated
Requesting --> Success : HTTP 200 received
Requesting --> RateLimited : HTTP 429 received
Requesting --> ServerError : HTTP 500+ received
Requesting --> Timeout : Request timed out
Requesting --> NetworkError : DNS / connection failure
Success --> Available : Ready for next request
RateLimited --> BackingOff : Enter exponential backoff
BackingOff --> Requesting : After backoff delay (2^n * 1s)
ServerError --> Available : Error logged, next request allowed
Timeout --> Available : Timeout logged, retry allowed
NetworkError --> Unavailable : Connection lost
Unavailable --> Checking : Periodic health check (30s)
note right of Available
Nominal state.
Cache hit rate: ~70%
Avg latency: ~200ms
end note
note right of BackingOff
Exponential backoff:
Attempt 1: 1s
Attempt 2: 2s
Attempt 3: 4s
Then fail.
end note
πΎ Cache Entry States
stateDiagram-v2
[*] --> Empty : Cache initialized (0 entries)
Empty --> Fresh : First data stored
Fresh --> Fresh : Cache hit (GET resets age if updateAgeOnGet=true)
Fresh --> Stale : TTL expires (15 minutes)
Stale --> Evicted : allowStale=false - entry removed on access
Stale --> Evicted : LRU eviction (capacity=500 reached)
Empty --> Full : 500 entries stored
Full --> Full : LRU eviction makes space for new entry
Full --> Fresh : New entry replaces evicted entry
Evicted --> [*] : Entry removed from memory
note right of Fresh
Entry age: 0 - 14:59
Served directly from cache
Latency: ~1ms
end note
note right of Stale
Entry age: 15:00+
allowStale=false means
stale entries are not
returned to callers
end note
note right of Full
500 entries = max capacity
New writes trigger LRU eviction
of least recently used entry
end note
β±οΈ Rate Limiter States
stateDiagram-v2
[*] --> FullBucket : Initialized (100 tokens)
FullBucket --> FullBucket : Request granted, token consumed, refill > consumption
FullBucket --> PartialBucket : Request granted, token consumed
PartialBucket --> PartialBucket : Requests granted, tokens fluctuating
PartialBucket --> EmptyBucket : All 100 tokens consumed
PartialBucket --> FullBucket : No requests, tokens refilled to 100
EmptyBucket --> Throttling : New request arrives
Throttling --> EmptyBucket : Request rejected (no token granted)
EmptyBucket --> PartialBucket : Time passes, tokens refill
note right of FullBucket
tokens = 100
Burst capacity available.
Refill rate: ~1.67/second
(100/minute)
end note
note right of EmptyBucket
tokens = 0
All requests rejected
until refill occurs.
Retry-after: varies
end note
note right of Throttling
RateLimitError thrown.
Propagated to tool handler.
Logged in AuditLogger.
Counted in MetricsService.
end note
ποΈ DI Container States
stateDiagram-v2
[*] --> Uninitialized : Container created
Uninitialized --> Registering : register() called
Registering --> Registering : Additional services registered
note right of Registering
Services registered:
1. RateLimiter
2. MetricsService
3. AuditLogger
4. HealthService
5. LRU Cache
6-14. EP API Clients (9)
end note
Registering --> Sealed : All services registered
Sealed --> Resolving : resolve() called for service
Resolving --> Ready : All singletons instantiated
Ready --> Ready : Normal operation, singletons served
Ready --> Disposing : Server shutdown initiated
Disposing --> Disposed : All services cleaned up
Disposed --> [*]
note right of Ready
Singletons active:
- RateLimiter (1 instance)
- MetricsService (1 instance)
- AuditLogger (1 instance)
- HealthService (1 instance)
Shared across all 62 tools
end note
π Data Availability States
State machine for OSINT data quality assessment. Each metric in an OSINT tool output transitions through availability states based on EP API data completeness:
stateDiagram-v2
[*] --> Checking : OSINT tool executes
Checking --> Available : EP API returns complete data
Checking --> Partial : EP API returns incomplete data
Checking --> Estimated : No direct data, proxy metrics used
Checking --> Unavailable : EP API returns no relevant data
Available --> HighConfidence : MetricResult computed
Partial --> MediumConfidence : MetricResult computed with gaps
Estimated --> LowConfidence : MetricResult derived from proxy
Unavailable --> NoConfidence : MetricResult value is null
HighConfidence --> QualityCheck : Validate metric
MediumConfidence --> QualityCheck : Add warning
LowConfidence --> QualityCheck : Add proxy warning
NoConfidence --> QualityCheck : Add unavailable warning
QualityCheck --> OutputReady : Assemble OsintStandardOutput
OutputReady --> [*] : Return with dataQualityWarnings
note right of Available
DataAvailability.AVAILABLE
All required data retrieved.
Confidence: HIGH
No warnings needed.
end note
note right of Partial
DataAvailability.PARTIAL
Some data retrieved.
Confidence: MEDIUM
Warning: partial data.
end note
note right of Estimated
DataAvailability.ESTIMATED
Metric derived from proxy
or indirect data sources.
Confidence: LOW
end note
note right of Unavailable
DataAvailability.UNAVAILABLE
EP API does not expose
required data. Value is null.
Confidence: NONE
end note
ποΈ Procedure Lifecycle States
The monitor_legislative_pipeline tool projects EP procedures onto an authoritative event-driven state machine sourced from /procedures/{id}/events. Each transition has a measurable dwell time used to compute percentile-based bottleneck risk and historical-median completion forecasts. The track_legislation tool also enriches its timeline with /events data but does not compute dwell percentiles or forecasts.
stateDiagram-v2
[*] --> REFERRAL: Procedure initiated
REFERRAL --> COM_VOTE: Committee adopts report
REFERRAL --> REJECTION: Withdrawn / rejected
COM_VOTE --> EP_ADOPTION: Plenary adopts position
COM_VOTE --> REJECTION: Plenary rejects
EP_ADOPTION --> SIGNATURE: Co-legislator agreement
EP_ADOPTION --> REJECTION: Council rejects
SIGNATURE --> [*]: Published in OJ
REJECTION --> [*]: Procedure closed
note right of REFERRAL
Stage key derived from
the normalized type of the
latest /procedures/{id}/events
entry (URI prefix stripped,
uppercased).
end note
note right of COM_VOTE
daysInCurrentStage =
now - latestEvent.date
bottleneckRisk:
HIGH if dwell β₯ p95
MEDIUM if dwell β₯ median
LOW otherwise
end note
note right of SIGNATURE
forecastBasis:
HISTORICAL_MEDIAN when
(type, stage) cell has
β₯3 samples in the corpus.
Otherwise INSUFFICIENT_DATA.
end note
The exact set of stage transitions depends on the EP API's event taxonomy (def/ep-activities/*). The diagram above shows the canonical happy-path lifecycle for COD procedures; NLE, BUD, and other types use the same machinery with their own observed stage distributions.
See FUTURE_STATEDIAGRAM.md for planned state management enhancements including streaming response states, real-time subscription states, and OAuth session states.