Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

AWS Agent Core — Jira Readiness Agent

A LangGraph agent on the bedrock-agentcore Python SDK that ingests Jira webhooks, assesses whether a Story / Task / Bug has enough information for implementation, and posts a structured Jira comment back through the mcp-internal HTTP MCP server. The repository ships one application with two deployment profiles selected at the composition root: a local profile (Docker Desktop Kubernetes + LocalStack + the Anthropic Messages API) for development, and an AWS profile (managed Amazon Bedrock AgentCore Runtime + DynamoDB + Bedrock + Secrets Manager) for production — application and domain code do not change between them. The reference implementation is Python; the architecture (see docs/ARCHITECTURE.md) is portable to any language whose runtime can satisfy the same Ports. AWS-only deferrals are owned by the production-only Terraform modules and scripts under terraform/ and scripts/.

Portable by design. The architecture document is language-agnostic on purpose — a JVM, .NET, Node, or Go runtime can satisfy the same Ports and remain a valid implementation. This README is the Python-specific counterpart that names concrete file paths, dependencies, and make targets; if you are evaluating a port to a different language, start with docs/ARCHITECTURE.md and treat this README as the reference implementation cookbook.

Cost shape note. Every "ready" assessment burns two Bedrock invocations, not one (see §Two-runnable cost trade): the bind_tools runnable drives the assessor's exploration loop until it has enough evidence, then a separate with_structured_output(TicketAssessment) invocation produces the validated decision. When the design branch fires it adds the same two-phase pattern (designer bind_tools → designer with_structured_output(ImplementationPlan)). Budget the AWS profile's per-tenant token cap accordingly: a single issue-updated webhook that triggers the design branch can consume up to four Bedrock invocations end-to-end. The Wave 5 Bedrock Guardrails run on every one of those invocations so a guardrail block fails fast at step 3 of the seven-step governance ordering (§Token governance).

Architecture at a glance

The structural roles below are language-agnostic (full description in docs/ARCHITECTURE.md); the "Reference impl" link points to where each role lives in the current Python codebase.

  • Domain Model — immutable, validated value objects (events, envelope, assessment, state, errors). No I/O. Reference impl: src/agent/domain/.
  • Ports — interfaces only; the dependency-inversion seam every Adapter binds to. Reference impl: src/agent/contracts/.
  • Application Services — pure use cases (webhook handler, normalizer, recursion guard, idempotency, assessor, runtime, comment renderer). Reference impl: src/agent/application/.
  • Adapters — concrete implementations of every Port (cloud SDK clients, MCP HTTP client, LLM provider client, telemetry SDK, persistent stores, messaging, ...). Reference impl: src/agent/infrastructure/.
  • Composition Root — the only place provider SDKs are named, one factory per profile. Two factories ship today: build_default_dependencies(...) (in-memory; tests only) and build_local_dependencies(...) (LocalStack + Anthropic; the local profile). build_aws_dependencies(...) lands in a follow-up milestone. Reference impl: src/agent/composition.py.
  • Entrypoint Wrapper — env-var-driven module that selects the profile and starts the runtime. AGENT_PROFILE=local selects the local factory; AGENT_PROFILE=aws is reserved for a follow-up milestone. Reference impl: src/agent/main.py.

High-level system context — one signed Jira webhook becomes one posted Jira comment. The same Application and Domain code runs in both deployment profiles; only the Adapters wired by the Composition Root change.

flowchart LR
    jira["Jira Cloud webhook"]
    tunnel["Ingress<br/>(local: tunnel; AWS: API Gateway / ALB)"]
    entry["Runtime Entrypoint<br/>(/invocations)"]
    handler["Webhook Handler<br/>signature -> normalize -><br/>recursion guard -> idempotency"]
    workflow["Agent Workflow Graph<br/>(checkpointed by thread_id)"]
    runtime["Agent Use Case<br/>fetch -> assess -> comment -> persist"]
    govern["Governed LLM Decorator<br/>budget + breaker + cost + observer"]
    mcp["mcp-internal MCP server<br/>(streamable HTTP + bearer)"]
    llm["LLM Provider"]
    dynamo[("Persistent stores<br/>idempotency / domain-state /<br/>tenants / token-budgets")]
    s3[("Raw payload archive")]
    sqs[("Dead-letter queue")]
    obs["Observability sinks<br/>(traces / metrics / logs)"]
    jiraApi["Jira REST API"]

    jira --> tunnel --> entry --> handler --> workflow --> runtime
    runtime -->|"MCP tools"| mcp --> jiraApi
    runtime --> govern --> llm
    handler -.-> dynamo
    runtime -.-> dynamo
    handler -.-> s3
    handler -.-> sqs
    handler -.-> obs
    runtime -.-> obs
    govern -.-> obs
Loading

Adapter boundary rule. Vendor SDKs and network libraries (cloud SDK, LLM provider client, HTTP client, telemetry SDK) are imported only from the Adapter and Composition modules — never from Application or Domain. The dependency direction is Entrypoint → Composition → Adapters → Ports → Domain, rendered in the layered diagram in docs/ARCHITECTURE.md. The current Python implementation enforces this with a static type checker plus a 100% line/branch coverage gate (concretely: boto3, langchain_aws, langchain_anthropic, bedrock_agentcore, httpx, and opentelemetry are only imported inside src/agent/infrastructure/ and src/agent/composition.py); a JVM implementation would enforce it with ArchUnit, .NET with NetArchTest, Node with dependency-cruiser, etc.

Diagrams

The high-level system context lives inline above. Four drill-down diagrams live in docs/ARCHITECTURE.md:

  • Layered / dependency direction — docs/ARCHITECTURE.md#layered-architecture. Domain Model → Ports (interfaces) → Application Services → Adapters → Composition Root → Entrypoint Wrapper, with the key Ports and the Adapters that bind to them.
  • Deployment topology (local sandbox vs AWS profile) — docs/ARCHITECTURE.md#deployment-topology. Side-by-side view of the local sandbox pods (Agent Runtime Pod, mcp-internal Pod, local trace collector, cloud-service simulator) vs the AWS profile (Managed Agent Runtime, Managed LLM Service, persistent stores, object store, dead-letter queue, Secrets Manager, Managed Memory + Identity + Observability), and the composition-root
    • IaC promotion path between them.
  • End-to-end flow — docs/ARCHITECTURE.md#end-to-end-flow. Sequence diagram for the make smoke path: Signature Verifier → Event Normalizer → Recursion Guard → Idempotency Service → Agent Workflow Graph (assess node) → Jira MCP Adapter (jira.get_issue) → Governed LLM Decorator → Comment Renderer → Jira MCP Adapter (jira.add_comment) → Domain State Store, with every span name, metric, and log line annotated.
  • Token governance + observability detail — docs/ARCHITECTURE.md#token-governance. The 7-step ordering invariant inside the Governed LLM Decorator (enforcer.check → breaker.before_call → metered.assess → cost.usd_for → enforcer.commit → observer.on_usage → breaker.record_success), plus the fan-out to the structured llm.usage log line, OTel GenAI semconv span attributes, and the gen_ai.client.token.usage / gen_ai.client.cost.usd histograms.

Two deployment profiles

The three rows below are the ones a contributor most often picks between (see docs/ARCHITECTURE.md#deployment-topology for the full local-vs-AWS contrast).

Profile Target environment LLM When to use
Local development Docker Desktop Kubernetes + LocalStack + sibling mcp-internal Pod langchain_anthropic.ChatAnthropic with ANTHROPIC_API_KEY Fast iteration, hot-reload, deterministic unit tests. AWS credentials are not required (the SDK is provider-agnostic).
Self-managed EKS / ECS / Fargate Customer-owned container platform in AWS langchain_aws.ChatBedrock against Amazon Bedrock Operator owns the platform; the SDK process is the only AWS-managed dependency.
Enterprise AgentCore Runtime Managed Amazon Bedrock AgentCore Runtime langchain_aws.ChatBedrock + AgentCore Memory + AgentCore Identity + AgentCore Observability Enterprise runtime, governance, autoscaling, managed Memory / Identity / Observability. Promotion is composition-root + IaC only.

Prerequisites

These prerequisites cover the infrastructure that supports the core project. The Python project's own prerequisites (interpreter version, virtualenv, optional extras) are covered in docs/PYTHON_DEVELOPMENT.md.

  • Docker Desktop with the built-in single-node Kubernetes cluster enabled.
  • kubectl (brew install kubernetes-cli on macOS).
  • Git LFS — the mcp-internal Spring Boot fat-JAR is tracked in LFS via .gitattributes. Install with brew install git-lfs (or apt-get install git-lfs on Linux), then run git lfs install and git lfs pull.
  • awslocal CLI (pipx install awscli-local) or the standard aws CLI configured with dummy credentials and --endpoint-url=http://localhost:4566.
  • Anthropic API key (sk-ant-…) — get one from https://console.anthropic.com. The agent runtime needs it at request time even when only the infrastructure is up (the mcp-internal Pod is bound to JIRA_* credentials, not the LLM).
  • Local LLM extras. The local profile's langchain_anthropic.ChatAnthropic factory is gated behind the [anthropic] optional extras block in pyproject.toml. The Pod image already bakes this in via Dockerfile; engineers running the bare-metal python -m agent.main path must install it explicitly: pip install -e ".[dev,anthropic]". Production AWS images must not install [anthropic] — [aws] covers the Bedrock + AgentCore Memory pins instead.
  • Optional: smee CLI or ngrok for tunneling real Jira Cloud webhooks (see deploy/local/README.md).

Infrastructure quickstart

The targets below bring up the supporting infrastructure for the core project: the mcp-internal Pod, the agent runtime image, LocalStack (DynamoDB / S3 / SQS / Secrets Manager), and Jaeger. Every target name is part of the frozen developer-command vocabulary; do not rename them (see Makefile for the source of truth).

git clone <repo-url>
cd aws-agent-core
git lfs install && git lfs pull        # materialises mcp/mcp-internal-*.jar

make build-mcp                         # build mcp-internal/server:local from mcp/Dockerfile
make build-agent                       # build aws-agent-core/agent-runtime:local from /Dockerfile
make local-up                          # kubectl apply -k deploy/local/
make seed-localstack                   # idempotent: creates DynamoDB tables, S3 bucket, SQS queue
make port-forward                      # in another terminal — agent on http://localhost:8080
make jaeger                            # opens the Jaeger trace UI at http://localhost:16686
make doctor                            # health-check: kubectl context, images, namespace, deployments
Target Purpose
make build-mcp Build the mcp-internal/server:local image from mcp/Dockerfile (wraps scripts/build_mcp_image.sh; resolves mcp/mcp-internal-*.jar).
make build-agent Build the aws-agent-core/agent-runtime:local image from the repo-root Dockerfile (wraps scripts/build_local_image.sh).
make local-up kubectl apply -k deploy/local/ (creates namespace, Secrets, all Pods/Services).
make local-down kubectl delete -k deploy/local/ (cluster-scoped resources stay).
make local-logs kubectl logs -f -n aws-agent-core-local deploy/agent-runtime.
make port-forward kubectl port-forward svc/agent-runtime 8080:8080.
make seed-localstack Creates idempotency, domain-state, tenants DynamoDB tables, the raw-payloads S3 bucket (versioned), and the agent-dlq SQS queue. Idempotent.
make jaeger Port-forwards jaeger-ui and opens http://localhost:16686.
make doctor Probes local-stack prerequisites: kubectl context, locally-built images, namespace, and the three core Deployments.
make tunnel-smee Documentation only: prints the smee / ngrok invocation.

For the smee.io / ngrok playbook and the host-mount kustomize overlay, see deploy/local/README.md.

Once the infrastructure quickstart is green, see docs/PYTHON_DEVELOPMENT.md to install the Python project, run smoke tests (make smoke, make smoke-recursion) and quality gates (make ci), and iterate against this infrastructure (including the make local-up-watch hot-reload loop and the bare-metal python -m agent.main path).

Environment variables (frozen contract)

The full env-var ↔ k8s Secret ↔ AWS Secrets Manager ↔ composition-root mapping lives in .env.local.example and deploy/local/configmap.yaml. The local-profile subset is reproduced here; AWS-only rows are footnoted below.

Env var Local default Consumed by
AGENT_PROFILE local agent.main selects build_local_dependencies vs build_aws_dependencies.
AGENT_BUDGET_SCOPE required when AGENT_PROFILE=local (set to local-pod-dev) Single-pod-dev acknowledgement gate in agent.main._resolve_local_dependencies. The local profile wires InMemoryTokenBudgetEnforcer (per-pod heap counters); without AGENT_BUDGET_SCOPE=local-pod-dev startup raises a ValueError so a misconfigured multi-replica staging deploy fails loud rather than silently over-permitting budgets. The AWS profile ignores this var (DynamoDbTokenBudgetEnforcer is cluster-shared).
ANTHROPIC_API_KEY required (sk-ant-…) anthropic_model_factory(api_key=…) (local).
ANTHROPIC_MODEL claude-sonnet-4-5-20250929 anthropic_model_factory(model_id=…). Pinned in lockstep with BEDROCK_MODEL_ID.
MCP_BASE_URL http://mcp-internal:8081/mcp HttpStreamableMcpClient(base_url=…).
MCP_BEARER_TOKEN literal DAVIDSUPERSECRETTOKEN HttpStreamableMcpClient(bearer_token=…). The same Secret value is exposed to the mcp-internal Pod as MCP_AUTH_TOKEN (the JAR's env-var name).
JIRA_SITE_URL / JIRA_EMAIL / JIRA_API_TOKEN from .env.local → jira-credentials k8s Secret Consumed by the mcp-internal Pod env, never by the agent runtime (single-integration-user rule). Confluence reuses the same triple inside the JAR.
LOCALSTACK_ENDPOINT_URL http://localstack:4566 every boto3 client factory in infrastructure/dynamodb/, …/storage/, …/messaging/.
AWS_REGION us-east-1 every boto3 client factory.
AGENT_JIRA_ACCOUNT_ID local-bot-account-id ActorIdentityRecursionGuard(agent_account_id=…) -- skips inbound webhooks whose actor.account_id matches the agent. Required.
AGENT_JIRA_EMAIL local-bot@example.test ActorIdentityRecursionGuard(agent_email=…) -- skips inbound webhooks whose actor.email matches the agent (case-insensitive). Required.
OBSERVABILITY_BACKEND jaeger tracer factory in agent.composition (xray lands in M5.5).
TOKEN_BUDGET_INPUT_PER_HOUR unset (no cap) InMemoryTokenBudgetEnforcer / DynamoDbTokenBudgetEnforcer input-token cap per rolling window.
TOKEN_BUDGET_OUTPUT_PER_HOUR unset (no cap) Output-token cap per rolling window.
TOKEN_BUDGET_USD_PER_WINDOW unset (no cap) USD cap per rolling window (computed via StaticCostCalculator).
TOKEN_BUDGET_WINDOW_SECONDS 3600 Rolling-window length used by both enforcer implementations.
TOKEN_BUDGET_TABLE_NAME unset → in-memory When set under AGENT_PROFILE=aws, switches to the DynamoDB-backed enforcer (atomic UpdateItem ADD + TTL).
LLM_CIRCUIT_FAIL_MAX 5 InMemoryLlmCircuitBreaker failure threshold.
LLM_CIRCUIT_RESET_SECONDS 30 Open-state cooldown before a half-open probe is scheduled.

AWS-only rows (omitted). BEDROCK_MODEL_ID, AGENTCORE_JWT_DISCOVERY_URL, and AGENTCORE_JWT_AUDIENCE apply only when AGENT_PROFILE=aws; their composition-root consumers land in a follow-up milestone. The contract is the union of .env.local.example, deploy/local/configmap.yaml, and the AWS-profile factory in src/agent/composition.py; a new env var must not land in code without updating those files in lockstep.

Token usage governance & cost attribution

The governance design ratified in docs/adr/ADR-001-token-governance.md adds a deterministic governance pipeline around every LLM call. Both deployment profiles run the same code path; only the enforcer adapter changes:

  • GovernedAssessmentLanguageModel wraps the metered Bedrock / Anthropic model and enforces the ordering invariant enforcer.check → breaker.before_call → inner.assess_metered → cost.usd_for → enforcer.commit → observer.on_usage → breaker.record_success (or breaker.record_failure(exc) on any inner failure).
  • LangChainUsageCapturer extracts token counts via langchain_core.callbacks.UsageMetadataCallbackHandler, so cache-hit / cache-miss tokens are reported correctly for both providers.
  • InMemoryTokenBudgetEnforcer (local) and DynamoDbTokenBudgetEnforcer (AWS) enforce per-tenant token + USD budgets per rolling window. The DynamoDB variant uses an atomic UpdateItem ADD and a TTL'd tenant#window_start partition key.
  • InMemoryLlmCircuitBreaker is a hand-rolled three-state (closed/open/half-open) machine driven by Clock and tenacity.wait_random_exponential for the half-open probe schedule.
  • StaticCostCalculator is backed by a vendored LiteLLM-derived model_prices.json snapshot with cache-read pricing.
  • OpenTelemetry GenAI semconv recorders emit gen_ai.usage.{input,output,cache_read.input,cache_creation.input}_tokens span attributes, the gen_ai.client.token.usage Histogram, a structured llm.usage log line, and webhook-stage counters (webhook.received / webhook.processed / webhook.skipped / webhook.error) plus a webhook.duration_ms histogram via the new MetricsRecorder Protocol.
  • AgentCore Harness defense-in-depth is wired at the AWS edge: terraform/agentcore-runtime exposes harness_max_tokens / harness_max_iterations / harness_timeout_seconds so the runtime enforces an outer cap independently of the in-process enforcer.
  • CloudWatch GenAI Observability dashboard + Application Signals Transaction Search are provisioned by the new terraform/observability-cloudwatch-genai module.

TicketReadinessAssessor propagates BudgetExceededError and LlmCircuitOpenError without retrying so a tripped breaker / saturated budget cannot be amplified by the retry loop into double-charged spend.

Testing and quality gates

The Python merge gates (ruff, mypy --strict, pytest with --cov-fail-under=100) plus the make lint / make typecheck / make test / make ci parity targets are documented in docs/PYTHON_DEVELOPMENT.md. The same gates are enforced by .github/workflows/ci.yml.

Architecture and structural roles

The repository's structural roles are language-agnostic. The directory layout described below is the Python reference implementation of those roles — a JVM / .NET / Node / Go port has the same Ports but is not required to follow this layout. See docs/ARCHITECTURE.md for the full treatment.

  • Domain — immutable validated value objects, no I/O.
  • Ports — interfaces / protocols at every external boundary.
  • Application Services — use cases (Webhook Handler, Agent Use Case, Token Governance Decorator, Event Normalizer, Recursion Guard, Idempotency Service, Comment Renderer).
  • Adapters — concrete implementations of Ports against vendor SDKs.
  • Composition Root — single module wiring Adapters to Ports per profile.
  • Entrypoint Wrapper — env-var-driven module exposing app to the runtime.

The structural roles above are language-agnostic. The directory layout that satisfies them in the current Python reference implementation appears further down, in Python reference layout — a JVM / .NET / Node / Go port has the same Ports but is not required to follow that layout.

What's deferred to AWS production

Seven items can only be implemented or validated against a real AWS account. Each maps 1:1 to a Terraform module under terraform/ (or a companion script under scripts/):

  1. Bedrock Guardrails — managed content-policy thresholds, denied-topics, PII filters (LocalStack does not emulate Bedrock InvokeModel).
  2. Managed AgentCore Runtime capabilities — AgentCore Memory, Identity (OAuth/JWT), Observability, managed scaling and session continuity.
  3. AWS X-Ray exporter and segment shape — local OTLP→Jaeger covers span shape; the X-Ray daemon and sampling rules are AWS-only.
  4. Production AWS account governance — least-privilege IAM, SCP / Organizations boundaries, cross-account sts:AssumeRole chains.
  5. Production network / edge security posture — public TLS endpoint, WAF, ALB / API Gateway throttling, JWT authorizer, NetworkPolicy egress.
  6. KMS-CMK + Secrets Manager rotation + S3 Object Lock / lifecycle — real cryptographic semantics and rotation timers.
  7. Live mcp-internal image digest + bearer-token rotation — digest pin owned by the platform team, Secrets-Manager-backed token.

Each item maps 1:1 to a Terraform module under terraform/.

Promotion to AWS AgentCore Runtime

Promotion is composition-root + IaC only — no edits under src/agent/application/ or src/agent/domain/. The high-level checklist is:

  1. Swap the LLM provider client adapter to the Bedrock-backed implementation in the LLM factory (reference impl: ChatAnthropic(api_key=…) → ChatBedrock(model_id=…)).
  2. Swap the in-memory checkpointer adapter to the managed-memory checkpointer (reference impl: LangGraph MemorySaver() → AgentCoreMemorySaver(...), or add a DynamoDbSaver from langgraph-checkpoint-aws for double-write).
  3. Drop endpoint_url=$LOCALSTACK_ENDPOINT_URL from every boto3 client factory; default to AWS-region clients backed by the runtime IAM role.
  4. Replace DAVIDSUPERSECRETTOKEN with MCP_BEARER_TOKEN loaded from AWS Secrets Manager.
  5. Replace the colocated webhook Service with API Gateway + Lambda → SQS → AgentCore Runtime.
  6. Move every k8s Secret into AWS Secrets Manager with the runtime role granted secretsmanager:GetSecretValue.
  7. Enable AgentCore Observability and re-validate every production-only deliverable against the real AWS account.
  8. agentcore configure --entrypoint src/agent/main.py and agentcore deploy (see src/agent/main.py).

A follow-up milestone ships build_aws_dependencies(...), terraform/agentcore-runtime/, .bedrock_agentcore.yaml, and scripts/promote_to_agentcore.sh to automate this.

Operations

On-call responders own docs/runbook.md, the single source of truth for incident response. It enumerates seven canonical scenarios — Bedrock Guardrail block, MCP outage, token-budget saturation, LLM circuit-breaker open, recursion-guard bypass, PII spill, and AgentCore Runtime drift — with the standard Symptom → Detect → Mitigate → Recover → Root-cause shape. Each Terraform module README links the same file so resource-owners can find the playbook from the cloud side too.

The operator-script catalogue lives next to the runbook:

Python reference layout

This section is Python-specific and is intentionally placed near the bottom of the README so a casual reader who only wants the language-agnostic story (architecture diagrams, deployment topology, production-only deferrals) is not greeted by Python directory paths first. A JVM / .NET / Node / Go port has the same Ports defined in docs/ARCHITECTURE.md but is not required to mirror this directory tree.

src/agent/
  domain/          # Pydantic value objects, no I/O
  contracts/       # Protocols (the IoC seam)
  application/     # Use cases (webhook handler, runtime, assessor,
                   #            token_governance.GovernedAssessmentLanguageModel, …)
  infrastructure/  # Adapters
    dynamodb/        #   idempotency, domain-state, token_budget_enforcer
    inmemory/        #   in-memory enforcers + stores (local profile)
    llm/             #   usage_capture.LangChainUsageCapturer + circuit_breaker
    cost/            #   static_calculator + vendored model_prices.json
    observability/   #   token_usage_recorder + otel_meter
    storage/  messaging/  mcp/  …
  composition/     # Composition root: build_{default,local,aws}_dependencies
  server.py        # bedrock-agentcore @app.entrypoint factory
  graph.py         # LangGraph StateGraph wrapping the agent
  main.py          # env-var-driven module-level `app` for agentcore deploy
tests/
  domain/  contracts/  application/  infrastructure/
  _doubles/        # FakeAssessmentLanguageModel, fake_governance, …
  fixtures/        # tests/fixtures/jira/*.json webhook corpus
deploy/local/      # Kubernetes manifests for the local stack
docs/adr/          # Architecture Decision Records (ADR-001 = token governance)
docs/runbook.md    # Incident-response runbook (guardrail / MCP / budget / DLQ)
Makefile           # Frozen developer-command vocabulary
scripts/           # smoke.py, promote_*.sh, export_token_usage.py
terraform/         # agentcore-runtime, observability-cloudwatch-genai, …

Contributing

License

This project is licensed under the Apache License, Version 2.0. See LICENSE for the full text.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages