{"id":30805550,"url":"https://github.com/aaronsb/petri-graph-template","last_synced_at":"2026-02-21T09:31:37.946Z","repository":{"id":304847090,"uuid":"1020238640","full_name":"aaronsb/petri-graph-template","owner":"aaronsb","description":null,"archived":false,"fork":false,"pushed_at":"2025-07-15T16:06:24.000Z","size":592,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-09-06T00:58:56.111Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TeX","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/aaronsb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-15T14:54:46.000Z","updated_at":"2025-08-29T21:47:26.000Z","dependencies_parsed_at":"2025-07-16T13:38:44.562Z","dependency_job_id":"29f3269a-4bde-4e65-b251-2eae798af38b","html_url":"https://github.com/aaronsb/petri-graph-template","commit_stats":null,"previous_names":["aaronsb/petri-graph-template"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/aaronsb/petri-graph-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aaronsb%2Fpetri-graph-template","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aaronsb%2Fpetri-graph-template/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aaronsb%2Fpetri-graph-template/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aaronsb%2Fpetri-graph-template/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aaronsb","download_url":"https://codeload.github.com/aaronsb/petri-graph-template/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aaronsb%2Fpetri-graph-template/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29678224,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-21T06:23:40.028Z","status":"ssl_error","status_checked_at":"2026-02-21T06:23:39.222Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-09-06T00:58:51.781Z","updated_at":"2026-02-21T09:31:37.930Z","avatar_url":"https://github.com/aaronsb.png","language":"TeX","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Colored Petri Net for MCP Tool Orchestration\n\nA **highly opinionated** approach to building functional, flexible toolkits for language model inference. This design pattern is backed by research and validated through multiple production implementations across diverse domains (enterprise systems, knowledge management, document authoring).\n\nRather than forcing rigid pathways, this approach embraces the inherent creativity and diversity of language models by presenting tools as an attractive field of possibilities.\n\n## 📄 Research Paper\n\nThis implementation is accompanied by a research paper that provides the theoretical foundation:\n\n**[Beyond Sequential Thinking: How Building an MCP Server Revealed Why AI Agents Fail at Enterprise Workflows](./semantic-petri-net-paper-july-2025.pdf)**\n\nThe paper documents the discovery of why finite state machine-based AI agents systematically fail at enterprise workflows, and how colored Petri nets provide a mathematical framework that aligns with how work actually happens. It includes the practical patterns that emerged during development and their theoretical validation.\n\n**Key insights from the paper:**\n- Why FSM-based agents create \"phone tree from hell\" experiences\n- How semantic hints encode Petri net output arcs\n- Why multi-entry workflows are essential for real-world usage\n- The information-theoretic foundation behind these patterns\n\n**Validation through production implementations:**\n- **[Salesforce MCP](https://github.com/aaronsb/salesforce-cloud)**: CRM workflow optimization (12+ API calls → 1 semantic operation)\n- **[Slack MCP](https://github.com/aaronsb/slack-mcp)**: Team coordination with OODA Loop patterns\n- **[Obsidian MCP](https://github.com/aaronsb/obsidian-semantic-mcp)**: Knowledge graph navigation (20+ tools → 5 semantic operations)\n- **[TeXFlow MCP](https://github.com/aaronsb/texflow-mcp)**: Document lifecycle intelligence (used to write the paper)\n- **[Targetprocess MCP](https://github.com/aaronsb/apptio-target-process-mcp)**: Project management workflows\n\nThese implementations demonstrate consistent emergence of semantic hinting patterns across diverse domains.\n\n## The Philosophy: APIs as Interpretative Landscapes\n\n### The Reality of Modern APIs\n\nAPIs in the wild rarely follow consistent design principles. They emerge from various sources:\n\n1. **Graph APIs** - Often lack logical traversal patterns, reflecting organic growth\n2. **Internal State Reflections** - Endpoints that mirror internal application architecture\n3. **Organizational Artifacts** - APIs exposed based on departmental boundaries or historical decisions\n4. **Utility Collections** - Endpoints added ad-hoc as needs arise\n\nAgent architectures that force these disparate endpoints into rigid state machines create friction between how APIs actually exist and how agents try to use them.\n\n### The Colored Petri Net Advantage\n\nInstead of forcing linear paths through API chaos, colored Petri nets create an **attractive field** where:\n\n- **Different models find different paths** - Each LLM's training biases become features, not bugs\n- **Creativity emerges from constraint** - The net provides structure while allowing stochastic exploration\n- **Tools combine naturally** - Verb:noun:verb patterns enable creative tool composition\n- **Context flows freely** - Tokens carry state through the net without rigid schemas\n\n## Core Innovation: Embracing Model Diversity\n\nDifferent language models have different:\n- **Training biases** - What they've seen shapes their preferences\n- **Architectural capabilities** - Some excel at planning, others at execution\n- **Stochastic tendencies** - Their \"creativity\" in approaching problems\n\nThe colored Petri net approach turns this diversity into a strength by:\n\n1. **Presenting all valid transitions** - Models choose based on their internal logic\n2. **Weighting paths with confidence scores** - Gentle guidance without forcing\n3. **Allowing novel combinations** - Unexpected tool sequences can emerge\n4. **Learning from choices** - Patterns can be analyzed to improve the net\n\n## Technical Foundation\n\n### Why Colored Petri Nets?\n\nWorkflow systems that model everything as single-state machines fail at scale. Real work is concurrent:\n\n```\nFSM Reality:                    Petri Net Reality:\nState = \"ReviewingTask\"         Token1 @ Review\n                               Token2 @ Implementation  \n                               Token3 @ Testing\n                               Token4 @ Documentation\n```\n\n### The Architecture\n\n```mermaid\ngraph TB\n    LM[Language Model]\n    MCP[MCP Server\u003cbr/\u003eTool Bridge]\n    CPN[Colored Petri Net]\n    \n    LM --\u003e|Calls tools| MCP\n    MCP --\u003e|Updates state| CPN\n    CPN --\u003e|Computes hints| MCP\n    MCP --\u003e|Returns results + hints| LM\n    \n    subgraph \"Petri Net Components\"\n        P1((Place 1))\n        P2((Place 2))\n        P3((Place 3))\n        T1[search꞉files]\n        T2[read꞉file]\n        T3[modify꞉file꞉write]\n        \n        P1 --\u003e|Token flow| T1\n        T1 --\u003e P2\n        P2 --\u003e T2\n        T2 --\u003e P3\n        P3 --\u003e T3\n    end\n    \n    style LM fill:#f9f,stroke:#333,stroke-width:2px,color:#000\n    style MCP fill:#bbf,stroke:#333,stroke-width:2px,color:#000\n    style CPN fill:#bfb,stroke:#333,stroke-width:2px,color:#000\n```\n\n## Core Components\n\n### 1. Colored Petri Net (`colored-petri-net.ts`)\nThe foundational data structure that creates an attractive field for AI navigation:\n- **Token Management** - Colored tokens carry rich context through the net\n- **Transition Discovery** - Computes all valid next actions, not just one\n- **Confidence Scoring** - Weights transitions based on context and history\n- **Pattern Matching** - Input arcs can filter tokens based on their color/data\n- **Expression Evaluation** - Output arcs transform tokens as they flow\n\n### 2. Semantic Hint Generation\nThe system doesn't dictate paths; it reveals possibilities:\n```typescript\ninterface SemanticHint {\n  transitionName: string;      // verb:noun or verb:noun:verb\n  confidence: number;          // 0-1, how attractive this option is\n  requiredTokens?: string[];   // What context is needed\n  example?: string;           // How to invoke it\n}\n```\n\nDifferent models will weight these hints differently based on their training and current context.\n\n### 3. MCP Server Integration (`mcp-petri-net-server.ts`)\nBridges the mathematical model with practical tool use:\n- **Dynamic Tool Prioritization** - Tools reorder based on workflow state\n- **Context Preservation** - Tokens flow between tool calls\n- **Emergent Workflows** - No predefined paths, just possibilities\n- **Model-Agnostic** - Works with any MCP-compatible LLM\n\n## Tool Naming Convention: Semantic Composability\n\nThe verb:noun:verb pattern isn't just naming—it's semantic composition:\n\n### Simple Tools (verb:noun)\n- `search:files` - Atomic action on a resource\n- `read:file` - Direct operation\n- `validate:schema` - Single-step process\n\n### Composite Tools (verb:noun:verb)\n- `search:file:read` - Workflow compression\n- `modify:file:write` - Transactional operation\n- `analyze:code:refactor` - Complex workflow as single transition\n\nThis pattern allows models to:\n1. **Choose granularity** - Use atomic or composite tools based on confidence\n2. **Create novel combinations** - Patterns can emerge that weren't explicitly programmed\n3. **Express intent clearly** - The semantic structure guides proper usage\n\n## Usage\n\n\u003e **Note**: This is a reference implementation demonstrating the design pattern. The code represents a highly opinionated approach to building LLM toolkits based on research findings and production experience across multiple domains.\n\n### Installation\n```bash\nnpm install\nnpm run build\n```\n\n### Run the Demo\n```bash\nnpm run demo\n```\n\nThis shows how the Petri net tracks state and suggests next actions.\n\n### Start the MCP Server\n```bash\nnpm start\n```\n\nThe server can then be connected to any MCP-compatible AI system.\n\n### Development\n```bash\nnpm run dev      # Run with ts-node\nnpm run analytics # View workflow analytics\nnpm test         # Run tests\nnpm run lint     # Lint code\n```\n\n## Example Workflow\n\n```mermaid\nstateDiagram-v2\n    [*] --\u003e Start\n    Start --\u003e Search_Results: search꞉files\n    Search_Results --\u003e File_Content: search꞉file꞉read\n    File_Content --\u003e File_Written: write꞉file\n    File_Content --\u003e File_Written: modify꞉file꞉write\n    File_Written --\u003e [*]\n    \n    note right of Search_Results: Multiple paths available\u003cbr/\u003eModel chooses based on context\n    note right of File_Content: Concurrent operations possible\u003cbr/\u003eTokens can exist in multiple places\n```\n\n## Real-World Applications\n\n### 1. API Integration Mapping\nMap disparate API endpoints into a coherent workflow space:\n```typescript\n// API endpoints become transitions\naddTransition({\n  name: 'fetch:user:profile',\n  handler: async (token) =\u003e {\n    // Maps to GET /api/v2/users/{id}/profile\n    // or GraphQL query { user(id) { profile } }\n    // or REST endpoint /legacy/getUserInfo\n  }\n});\n```\n\n### 2. Multi-Model Orchestration\nDifferent models navigate the same net differently:\n- **GPT-4**: Might prefer compositional tools (verb:noun:verb)\n- **Claude**: Might chain atomic operations\n- **Specialized models**: Follow domain-specific paths\n\n### 3. Emergent Workflow Discovery\nThe net reveals patterns in how models solve problems:\n```typescript\n// Track transition sequences\nconst patterns = analyzer.findCommonPaths();\n// Discover that 90% of file edits follow: search → read → modify → write\n// But 10% use creative alternatives: search → analyze → regenerate\n```\n\n## Advanced Patterns\n\n### Conditional Transitions\nUse guards to create context-aware workflows:\n```typescript\naddTransition({\n  name: 'deploy:code:production',\n  guard: (binding) =\u003e {\n    return binding.tests_passed \u0026\u0026 \n           binding.review_approved \u0026\u0026 \n           binding.user_role === 'deployer';\n  }\n});\n```\n\n### Token Transformation\nColors (data) transform as tokens flow:\n```typescript\naddArc({\n  source: 'code_analyzed',\n  target: 'generate:refactor:plan',\n  expression: (token) =\u003e ({\n    ...token,\n    suggestions: analyzeCodeQuality(token.ast),\n    complexity: calculateCyclomaticComplexity(token.ast)\n  })\n});\n```\n\n### Hierarchical Nets\nCompose smaller nets into larger workflows:\n```typescript\nconst authNet = createAuthWorkflow();\nconst dataNet = createDataProcessingWorkflow();\nconst apiNet = composeNets(authNet, dataNet, {\n  bridges: [\n    { from: 'auth.token_acquired', to: 'data.api_ready' }\n  ]\n});\n```\n\n## Implementation Best Practices\n\n### 1. Design for Concurrency\n```typescript\n// Places should represent concurrent states\naddPlace({ id: 'files_processing', name: 'Files Being Processed' });\naddPlace({ id: 'api_calls_pending', name: 'Pending API Calls' });\naddPlace({ id: 'results_aggregating', name: 'Aggregating Results' });\n```\n\n### 2. Semantic Tool Naming\n```typescript\n// Good: Clear verb:noun:verb pattern\n'validate:schema:fix'\n'analyze:performance:optimize'\n\n// Avoid: Ambiguous or procedural names\n'processData'\n'handleRequest'\n```\n\n### 3. Rich Token Context\n```typescript\ninterface WorkflowToken {\n  id: string;\n  timestamp: number;\n  source: 'user' | 'system' | 'api';\n  data: any;\n  history: TransitionHistory[];\n  metadata: Record\u003cstring, any\u003e;\n}\n```\n\n## Scaling Considerations\n\n### For Large APIs\n- **Lazy Loading**: Load transitions on demand\n- **Clustering**: Group related transitions\n- **Caching**: Cache enabled transition calculations\n- **Sharding**: Distribute net across services\n\n### For Multiple Models\n- **Model Profiles**: Track preferences per model\n- **A/B Testing**: Compare path efficiencies\n- **Adaptation**: Adjust confidence scores dynamically\n\n## Theory and Practice\n\nThe approach builds on established Petri net theory while addressing practical AI agent needs:\n\n1. **Formal Foundation**: Mathematical proofs of correctness possible\n2. **Practical Flexibility**: Handles messy real-world APIs\n3. **Model Diversity**: Embraces different AI capabilities\n4. **Emergent Behavior**: Enables creative problem-solving\n\n## Getting Started with Your Own Implementation\n\n### 1. Define Your Domain\nStart by mapping your API or tool landscape:\n```typescript\n// Identify your places (states)\nconst places = [\n  'data_needed',\n  'data_fetched', \n  'data_validated',\n  'data_processed'\n];\n\n// Map your tools to transitions\nconst transitions = [\n  { name: 'fetch:data', from: 'data_needed', to: 'data_fetched' },\n  { name: 'validate:data', from: 'data_fetched', to: 'data_validated' },\n  { name: 'process:data:save', from: 'data_validated', to: 'data_processed' }\n];\n```\n\n### 2. Add Domain Logic\nImplement guards and expressions for your specific needs:\n```typescript\nnet.addTransition({\n  name: 'approve:document',\n  guard: (binding) =\u003e binding.document_token.status === 'pending_review',\n  handler: async (binding) =\u003e {\n    const result = await documentAPI.approve(binding.document_token.id);\n    return { ...binding.document_token, status: 'approved', approver: binding.user };\n  }\n});\n```\n\n### 3. Connect to MCP\nWire your net to the Model Context Protocol:\n```typescript\nconst server = new MCPPetriNetServer();\nserver.loadNet(yourCustomNet);\nawait server.start();\n```\n\n## Troubleshooting\n\n### Common Issues\n\n**\"No enabled transitions\"**\n- Check that tokens exist in places\n- Verify guard conditions\n- Ensure arcs are properly connected\n\n**\"State explosion\"**\n- Use hierarchical nets for complex workflows\n- Consider token attributes instead of separate places\n- Group similar states\n\n**\"Poor model performance\"**\n- Adjust confidence scoring algorithms\n- Provide richer semantic hints\n- Consider model-specific adaptations\n\n## Workflow Analytics\n\nThe MCP server includes a **lightweight analytics logger** that captures how language models navigate the semantic space. This enables empirical validation of the theoretical patterns described in the research paper.\n\n### Features\n\n- **Session Tracking**: Automatically groups tool calls into sessions with configurable timeouts\n- **Petri Net Metrics**: Captures token flow, confidence scores, and transition patterns\n- **Path Analysis**: Discovers common workflows and model preferences\n- **Error Tracking**: Identifies where transitions fail and why\n- **Lightweight Design**: Uses JSON Lines format, no external dependencies\n\n### Usage\n\n```bash\n# View real-time analytics\nnpm run analytics\n\n# Show design insights\nnpm run analytics insights\n```\n\n### Configuration\n\nConfigure via environment variables:\n\n```bash\nexport MCP_LOG_PATH=./workflow-logs        # Log storage location\nexport MCP_SESSION_TIMEOUT_MINUTES=10      # Session timeout\nexport MCP_LOGGING_ENABLED=true            # Enable logging\nexport MCP_LOG_LEVEL=info                  # Log level\n```\n\nThe analytics validate key research claims:\n- Models use multiple entry points (not linear workflows)\n- Confidence scores correlate with successful transitions\n- Different models discover different paths through the same net\n- Semantic hints guide navigation effectively\n\nSee [workflow-logger.md](src/workflow-logger.md) for detailed documentation.\n\n## Resources\n\n- [Petri Net Theory](https://www.informatik.uni-hamburg.de/TGI/PetriNets/)\n- [Model Context Protocol](https://modelcontextprotocol.io/)\n- [Example Implementations](./examples/)\n\n## Contributing\n\nWe welcome contributions that:\n- Add new workflow patterns\n- Improve semantic hint generation\n- Extend to new domains\n- Enhance model compatibility\n\nPlease include tests and documentation with your contributions.\n\n## License\n\nMIT","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faaronsb%2Fpetri-graph-template","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faaronsb%2Fpetri-graph-template","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faaronsb%2Fpetri-graph-template/lists"}