### Run meta-protocol negotiation example Source: https://github.com/agent-network-protocol/anp/blob/master/CLAUDE.md Runs the meta-protocol negotiation example. Requires Azure OpenAI configuration in .env. Start Bob first, then Alice. ```bash # Meta-protocol negotiation (requires Azure OpenAI config in .env) uv run python examples/python/negotiation_mode/negotiation_bob.py # Start Bob first uv run python examples/python/negotiation_mode/negotiation_alice.py # Then Alice ``` -------------------------------- ### Run Dart examples Source: https://github.com/agent-network-protocol/anp/blob/master/docs/examples.md Run the Dart examples from the dart package directory. Requires 'dart pub get' first. ```bash cd dart dart pub get dart run example/create_did_document.dart dart run example/authentication_http_signature.dart dart run example/proof.dart dart run example/wns.dart ``` -------------------------------- ### Install dependencies with uv sync --extra api Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/openanp_examples/README.md Installs project dependencies including the api extra, required for running the examples. ```bash # Install dependencies (requires api extra) uv sync --extra api ``` -------------------------------- ### Run example scripts Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/docs/getting-started.md Build the SDK and execute the provided example scripts. ```bash npm run build node examples/authentication.mjs node examples/proof.mjs node examples/wns.mjs ``` -------------------------------- ### Run SDK Examples Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/examples/README.md Commands to execute the authentication, proof, and WNS module examples. ```bash node examples/authentication.mjs node examples/proof.mjs node examples/wns.mjs ``` -------------------------------- ### Run Minimal Example Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/openanp_examples/README.md Starts the minimal server with uvicorn on port 8000 and runs the minimal client in a second terminal. ```bash # Terminal 1: Start server uvicorn examples.python.openanp_examples.minimal_server:app --port 8000 # Terminal 2: Run client uv run python examples/python/openanp_examples/minimal_client.py ``` -------------------------------- ### Run OpenANP minimal example Source: https://github.com/agent-network-protocol/anp/blob/master/CLAUDE.md Runs the OpenANP minimal example. Start the server in one terminal with uvicorn on port 8000, then run the client in a second terminal. Requires the --extra api dependencies. ```bash # OpenANP examples (recommended starting point, requires --extra api) uvicorn examples.python.openanp_examples.minimal_server:app --port 8000 # Terminal 1 uv run python examples/python/openanp_examples/minimal_client.py # Terminal 2 ``` -------------------------------- ### Example commands for generate_did_doc.py Source: https://github.com/agent-network-protocol/anp/blob/master/tools/did_generater/README_did_generater.md Three example invocations: basic usage, with agent description URL, and with verbose logging. The DID string must start with 'did:wba:'. ```bash # Basic usage python generate_did_doc.py "did:wba:service.agent-network-protocol.com:wba:user:lkcoffe" ``` ```bash # With agent description URL python generate_did_doc.py "did:wba:service.agent-network-protocol.com:wba:user:lkcoffe" --agent-description-url "https://example.com/agent.json" ``` ```bash # Enable detailed logging python generate_did_doc.py "did:wba:service.agent-network-protocol.com:wba:user:lkcoffe" -v ``` -------------------------------- ### Run Advanced Example Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/openanp_examples/README.md Starts the advanced server with uvicorn on port 8000 and runs the advanced client in a second terminal. ```bash # Terminal 1: Start server uvicorn examples.python.openanp_examples.advanced_server:app --port 8000 # Terminal 2: Run client uv run python examples/python/openanp_examples/advanced_client.py ``` -------------------------------- ### Build Java Maven Workspace Source: https://github.com/agent-network-protocol/anp/blob/master/docs/examples.md Initializes the local Maven workspace for Java examples by cleaning and installing dependencies. ```bash cd java mvn clean install -DskipTests ``` -------------------------------- ### Install ANP SDKs for Python, Go, Rust, Dart, and TypeScript Source: https://github.com/agent-network-protocol/anp/blob/master/README.md Minimal install commands for the published ANP SDKs. Python core is `pip install anp`; the `[api]` extra adds FastAPI and OpenAI dependencies. Go uses `go get` with the module path, Rust uses `cargo add`, Dart uses `dart pub add`, and TypeScript uses `npm install`. For local repository development, prefer the commands in the Development section instead. ```bash # Python core SDK pip install anp # Python agent-building extras: FastAPI + OpenAI dependencies pip install "anp[api]" # Go go get github.com/agent-network-protocol/anp/golang@latest # Rust cargo add anp # Dart dart pub add anp # TypeScript npm install @awiki/anp-typescript-sdk ``` -------------------------------- ### Run the direct E2EE example Source: https://github.com/agent-network-protocol/anp/blob/master/golang/examples/direct_e2ee/README.md Run the example with `go run ./examples/direct_e2ee`. The output prints each major step in English, including bundle publication, init-message send, follow-up send, pending state for out-of-order delivery, and successful decryption results for Bob and Alice. ```bash go run ./examples/direct_e2ee ``` -------------------------------- ### Run TypeScript examples Source: https://github.com/agent-network-protocol/anp/blob/master/docs/examples.md Run the TypeScript examples from the typescript/ts_sdk/examples directory. Requires Node.js 20+ and building the SDK first. ```bash cd typescript/ts_sdk npm install npm run build node examples/authentication.mjs node examples/proof.mjs node examples/wns.mjs ``` -------------------------------- ### Run Rust interop and network helper examples Source: https://github.com/agent-network-protocol/anp/blob/master/docs/examples.md Run the Rust interop and network helper examples from the rust crate directory. ```bash cd rust cargo run --example interop_cli cargo run --example interop_server cargo run --example direct_e2ee_interop_cli cargo run --example direct_e2ee_verify_fixture ``` -------------------------------- ### Run Go examples Source: https://github.com/agent-network-protocol/anp/blob/master/docs/examples.md Run the Go examples from the golang module directory. Use 'go test ./...' from golang/ for the full Go validation suite. ```bash cd golang go run ./examples/create_did_document go run ./examples/proof go run ./examples/wns go run ./examples/direct_e2ee ``` -------------------------------- ### User-Controlled Routes: Defining GET Endpoints Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/fastanp_examples/README.md Demonstrates that all routes are defined by the user. The example shows two GET endpoints: one for the agent description and one for custom info. ```python @app.get("/ad.json") def get_agent_description(): ad = anp.get_common_header() ad["interfaces"] = [...] return ad @app.get("/info/custom.json") def custom_info(): return {"data": "..."} ``` -------------------------------- ### Run DID WBA authentication examples Source: https://github.com/agent-network-protocol/anp/blob/master/CLAUDE.md Runs the DID WBA authentication examples. These are offline and require no extra dependencies. First create a DID document, then authenticate and verify. ```bash # DID WBA authentication examples (offline, no extra deps) uv run python examples/python/did_wba_examples/create_did_document.py uv run python examples/python/did_wba_examples/e1_authenticate_and_verify.py ``` -------------------------------- ### Build the SDK Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/examples/README.md Run this command to build the SDK before executing any examples. ```bash npm run build ``` -------------------------------- ### Call the agent with the example client Source: https://github.com/agent-network-protocol/anp/blob/master/README.md Run the repository's minimal client to call the agent. ```bash uv run python examples/python/openanp_examples/minimal_client.py ``` -------------------------------- ### Install ANP Library Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/anp_crawler_examples/README.md Two installation options for the ANP library: via pip or from source using uv. The source installation is recommended for developers. ```bash pip install anp ``` ```bash git clone https://github.com/agent-network-protocol/AgentConnect.git cd AgentConnect uv sync ``` -------------------------------- ### Run ANP Crawler example Source: https://github.com/agent-network-protocol/anp/blob/master/CLAUDE.md Runs the ANP Crawler example, a simple AMAP example. ```bash # ANP Crawler examples uv run python examples/python/anp_crawler_examples/simple_amap_example.py ``` -------------------------------- ### Run ANP crawler examples with uv Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/README.md Commands to run the simple and complete AMAP crawler examples. Requires uv and the example files in examples/python/anp_crawler_examples/. ```bash # Run simple example uv run python examples/python/anp_crawler_examples/simple_amap_example.py # Run complete example uv run python examples/python/anp_crawler_examples/amap_crawler_example.py ``` -------------------------------- ### Run Chat Example Agents Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/openanp_examples/README.md Starts two chat agents in separate terminals. Run chat_a.py in terminal 1 and chat_b.py in terminal 2. ```bash # Terminal 1: Start Chat Agent A uv run python examples/python/openanp_examples/chat_a.py # Terminal 2: Start Chat Agent B (in another terminal) uv run python examples/python/openanp_examples/chat_b.py ``` -------------------------------- ### Install ANP SDK with pip or uv Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/did_wba_examples/DID_WBA_AUTH_GUIDE.en.md Install the base ANP package using pip or uv. For FastAPI support, install with the 'api' extra. ```bash pip install anp # or using uv uv add anp ``` ```bash pip install anp[api] # or uv add anp --extra api ``` -------------------------------- ### discover_agent usage example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/API_PROPOSAL.md Example of calling discover_agent and iterating over discovered interfaces to print descriptions. ```python discovery = await client.discover_agent("http://localhost:8000/ad.json") if discovery["success"]: for interface in discovery["interfaces"]: print(f"Found interface: {interface['description']}") ``` -------------------------------- ### Run AP2 Payment Protocol example Source: https://github.com/agent-network-protocol/anp/blob/master/CLAUDE.md Runs the AP2 Payment Protocol complete flow example. ```bash # AP2 Payment Protocol example uv run python examples/python/ap2_examples/ap2_complete_flow.py ``` -------------------------------- ### Start DID-WBA HTTP Server Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/examples/README.md Build and start the TypeScript server for DID-WBA HTTP authentication. ```bash npm run build node examples/did-wba-http-server.mjs ``` -------------------------------- ### Install the SDK Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/docs/getting-started.md Use npm to install the ANP TypeScript SDK package. ```bash npm install @awiki/anp-typescript-sdk ``` -------------------------------- ### Run complete flow example Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/ap2_examples/README.md Command to run the complete AP2 flow example in a single process. ```bash uv run python examples/python/ap2_examples/ap2_complete_flow.py ``` -------------------------------- ### Create e1 DID: run create_did_document.py Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/did_wba_examples/README.md Runs the example that creates e1 DID material, writing DID document and key files to the generated/e1 directory. ```bash uv run python examples/python/did_wba_examples/create_did_document.py ``` -------------------------------- ### Run example scripts for authentication, proof, and WNS Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/README.md Execute these example scripts to see usage of authentication, proof, and WNS features. Each script is run with Node.js. ```bash node examples/authentication.mjs node examples/proof.mjs node examples/wns.mjs ``` -------------------------------- ### Run FastANP examples Source: https://github.com/agent-network-protocol/anp/blob/master/CLAUDE.md Runs the FastANP examples. Requires the --extra api dependencies. Includes a simple agent and a hotel booking agent. ```bash # FastANP examples (requires --extra api) uv run python examples/python/fastanp_examples/simple_agent.py uv run python examples/python/fastanp_examples/hotel_booking_agent.py ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/agent-network-protocol/anp/blob/master/docs/examples.md Install the necessary Python dependencies for local development using uv. ```bash uv sync uv sync --extra api ``` -------------------------------- ### Run Rust examples Source: https://github.com/agent-network-protocol/anp/blob/master/docs/examples.md Run the Rust examples from the rust crate directory. Use 'cargo test' from rust/ for the full Rust validation suite. ```bash cd rust cargo run --example create_did_document cargo run --example proof_example cargo run --example wns_example ``` -------------------------------- ### Run simple_agent_with_context.py Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/fastanp_examples/README.md Command to run the context injection example agent. ```bash cd /path/to/AgentConnect uv run python examples/python/fastanp_examples/simple_agent_with_context.py ``` -------------------------------- ### Run complete authentication: e1_authenticate_and_verify.py Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/did_wba_examples/README.md Runs the self-contained example that performs e1 DID creation, HTTP Message Signatures authentication, and Bearer token issuance and reuse. ```bash uv run python examples/python/did_wba_examples/e1_authenticate_and_verify.py ``` -------------------------------- ### Run hotel_booking_agent.py Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/fastanp_examples/README.md Command to run the complete hotel booking agent example. ```bash cd /path/to/AgentConnect uv run python examples/python/fastanp_examples/hotel_booking_agent.py ``` -------------------------------- ### Install OpenANP API extras with uv sync Source: https://github.com/agent-network-protocol/anp/blob/master/README.md When developing from the repository, use uv to sync the API extra. ```bash uv sync --extra api ``` -------------------------------- ### Install OpenANP API extras with pip Source: https://github.com/agent-network-protocol/anp/blob/master/README.md Install the published package with the API extras to use OpenANP. ```bash pip install "anp[api]" ``` -------------------------------- ### Install ANP with UV Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/README.md Install the ANP package using UV. ```bash uv sync ``` -------------------------------- ### get_information usage example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/API_PROPOSAL.md Example of calling get_information to fetch an information endpoint and printing the message field. ```python result = await client.get_information("http://localhost:8000/info/hello.json") if result["success"]: print(result["data"]["message"]) ``` -------------------------------- ### execute_tool_call example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/README.md Example of executing a discovered tool by name and arguments. ```python result = await crawler.execute_tool_call("search_poi", {"query": "Beijing"}) if result["success"]: print(f"Found: {result['result']}") ``` -------------------------------- ### Start the ANP Server Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/minimal_example/README.md Launch the minimal ANP server on localhost port 8000. ```bash cd /Users/moshiwei/Documents/GitHub/anp uv run python examples/python/minimal_example/minimal_anp_server.py ``` -------------------------------- ### get_agent_description usage example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/API_PROPOSAL.md Example of calling get_agent_description and accessing the interfaces from the returned data. ```python result = await client.get_agent_description("http://localhost:8000/ad.json") if result["success"]: interfaces = result["data"]["interfaces"] ``` -------------------------------- ### Run AMAP Crawler Examples Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/anp_crawler_examples/README.md Commands to run the simple and complete AMAP crawler examples. Both use uv run and require the DID authentication files to be present. ```bash uv run python examples/python/anp_crawler_examples/simple_amap_example.py ``` ```bash uv run python examples/python/anp_crawler_examples/amap_crawler_example.py ``` -------------------------------- ### Private key document JSON example (private_keys.json) Source: https://github.com/agent-network-protocol/anp/blob/master/tools/did_generater/README_did_generater.md Example structure of the private key document, containing the DID and key information with path and type. ```json { "did": "did:wba:service.agent-network-protocol.com:wba:user:lkcoffe", "keys": { "key-1": { "path": "key-1_private.pem", "type": "EcdsaSecp256k1" } } } ``` -------------------------------- ### Run Java Standalone Examples Source: https://github.com/agent-network-protocol/anp/blob/master/docs/examples.md Executes specific Java main classes for DID document creation and authentication using the exec:java Maven plugin. ```bash cd java mvn exec:java -pl anp-examples -Dexec.mainClass="com.agentconnect.example.didwba.CreateDIDDocument" mvn exec:java -pl anp-examples -Dexec.mainClass="com.agentconnect.example.didwba.AuthenticateAndVerify" ``` -------------------------------- ### DID document format example (did.json) Source: https://github.com/agent-network-protocol/anp/blob/master/tools/did_generater/README_did_generater.md Example JSON structure of the generated DID document, including @context, id, verificationMethod with publicKeyJwk, and authentication. ```json { "@context": [ "https://www.w3.org/ns/did/v1", "https://w3id.org/security/suites/jws-2020/v1", "https://w3id.org/security/suites/secp256k1-2019/v1" ], "id": "did:wba:service.agent-network-protocol.com:wba:user:lkcoffe", "verificationMethod": [ { "id": "did:wba:service.agent-network-protocol.com:wba:user:lkcoffe#key-1", "type": "EcdsaSecp256k1VerificationKey2019", "controller": "did:wba:service.agent-network-protocol.com:wba:user:lkcoffe", "publicKeyJwk": { "kty": "EC", "crv": "secp256k1", "x": "...", "y": "...", "kid": "..." } } ], "authentication": [ "did:wba:service.agent-network-protocol.com:wba:user:lkcoffe#key-1" ] } ``` -------------------------------- ### JSON application content example Source: https://github.com/agent-network-protocol/anp/blob/master/docs/e2e/direct-e2ee-p5-sdk.md Example JSON payload for application content, showing the application_content_type and payload structure. ```json { "application_content_type": "application/json", "payload": { "type": "example", "data": { "hello": "world" } } } ``` -------------------------------- ### list_available_tools example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/README.md Returns a list of discovered tool names. ```python tools = crawler.list_available_tools() # ['search', 'book', 'cancel'] ``` -------------------------------- ### Usage Examples for fetch() Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/API_IMPROVEMENTS.md Demonstrates the unified fetch() method for three URL types: agent description, info endpoint, and any JSON URL. Each call returns a dictionary with a success flag and data. ```python # Fetch agent description agent_result = await client.fetch("http://localhost:8000/ad.json") if agent_result["success"]: agent_data = agent_result["data"] interfaces = agent_data.get("interfaces", []) # Fetch information endpoint hello_result = await client.fetch("http://localhost:8000/info/hello.json") if hello_result["success"]: message = hello_result["data"]["message"] # Fetch any JSON URL any_result = await client.fetch("http://example.com/data.json") if any_result["success"]: data = any_result["data"] ``` -------------------------------- ### fetch_text example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/README.md Example of calling fetch_text to retrieve content and tools from an Agent Description URL. ```python content, tools = await crawler.fetch_text("https://example.com/ad.json") print(f"Found {len(tools)} tools") ``` -------------------------------- ### content Example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/fastanp/README.md Example of content format, which embeds the OpenRPC document directly. ```python { "type": "StructuredInterface", "protocol": "openrpc", "description": "...", "content": { "openrpc": "1.3.2", "info": {...}, "methods": [...] } } ``` -------------------------------- ### Run simple_agent.py Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/fastanp_examples/README.md Command to run the minimal FastANP agent example. Requires navigating to the AgentConnect directory and using uv run. ```bash cd /path/to/AgentConnect uv run python examples/python/fastanp_examples/simple_agent.py ``` -------------------------------- ### link_summary Example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/fastanp/README.md Example of link_summary format, which is a URL reference to a separate JSON-RPC file. ```python { "type": "StructuredInterface", "protocol": "openrpc", "description": "...", "url": "https://example.com/info/search.json" } ``` -------------------------------- ### Install ANP via pip Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/README.md Install the ANP package using pip. ```bash pip install anp ``` -------------------------------- ### Run the server with uvicorn Source: https://github.com/agent-network-protocol/anp/blob/master/README.md Start the FastAPI server on port 8000. ```bash uvicorn app:app --port 8000 ``` -------------------------------- ### Validate DID: run validate_did_document.py Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/did_wba_examples/README.md Runs the example that validates the generated DID document. ```bash uv run python examples/python/did_wba_examples/validate_did_document.py ``` -------------------------------- ### Quick Start: Create DID and Authentication Headers Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/README.md Imports core functions from the SDK to create a DID document, generate legacy and signature headers, and verify a binding. Uses DidProfile.K1 and a sample DID document for verification. ```ts import { DidProfile, createDidDocument, createLegacyAuthHeader, createSignatureHeaders, verifyBinding, } from '@awiki/anp-typescript-sdk'; const bundle = createDidDocument('example.com', { pathSegments: ['agents', 'demo'], didProfile: DidProfile.K1, }); const legacyHeader = createLegacyAuthHeader( bundle.didDocument, 'api.example.com', bundle.keys['key-1'].privateKeyPem ); const signatureHeaders = createSignatureHeaders( bundle.didDocument, 'https://api.example.com/orders', 'POST', bundle.keys['key-1'].privateKeyPem, {}, '{"item":"book"}' ); const binding = await verifyBinding('alice.example.com', { didDocument: { '@context': ['https://www.w3.org/ns/did/v1'], id: 'did:wba:example.com:user:alice', verificationMethod: [], authentication: [], service: [ { id: 'did:wba:example.com:user:alice#handle', type: 'ANPHandleService', serviceEndpoint: 'https://example.com/providers/wns', }, ], }, }); ``` -------------------------------- ### execute_json_rpc example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/README.md Example of making a direct JSON-RPC call without interface discovery. ```python result = await crawler.execute_json_rpc( endpoint="https://example.com/rpc", method="search", params={"query": "hotel", "limit": 10} ) ``` -------------------------------- ### Test simple_agent.py with curl Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/fastanp_examples/README.md Curl commands to test the minimal agent: get agent description, get OpenRPC document, and call the hello method. ```bash # Get Agent Description curl http://localhost:8000/ad.json | jq # Get OpenRPC document curl http://localhost:8000/info/hello.json | jq # Call hello method curl -X POST http://localhost:8000/rpc \ -H "Content-Type: application/json" \ -d '{"jsonrpc": "2.0", "id": 1, "method": "hello", "params": {"name": "World"}}' ``` -------------------------------- ### Create AWiki IM client with AwikiImClientOptions Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/docs/configuration.md Use createAwikiImClient() with AwikiImClientOptions to create an AWiki IM client. The example configures service URLs, DID, attachment origins, max bytes, and state path. ```typescript const im = createAwikiImClient({ userServiceUrl: 'https://auth.internal.example', userServiceDomain: 'awiki.example', messageServiceUrl: 'https://messages.internal.example', messageServicePublicUrl: 'https://messages.awiki.example', messageServiceDid: 'did:wba:messages.awiki.example', allowedAttachmentOrigins: [ 'https://messages.awiki.example', 'https://objects.awiki.example', ], attachmentMaxBytes: 10 * 1024 * 1024, statePath: '/var/lib/my-agent/awiki-im.json', }); ``` -------------------------------- ### Minimal FastAPI + DID WBA Authentication Example Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/did_wba_examples/DID_WBA_AUTH_GUIDE.en.md Complete example showing how to add DID WBA authentication to a FastAPI server. It loads JWT keys, creates a verifier, registers middleware, and defines exempt and protected routes. The DID is injected into request.state.did after successful authentication. ```python """Minimal example of adding DID WBA authentication to a FastAPI server.""" from fastapi import FastAPI, Request from anp.authentication import DidWbaVerifier, DidWbaVerifierConfig from anp.openanp.middleware import auth_middleware # 1. Prepare JWT keys (RS256) # Generate with: openssl genrsa -out private.pem 2048 # openssl rsa -in private.pem -pubout -out public.pem with open("private.pem") as f: jwt_private_key = f.read() with open("public.pem") as f: jwt_public_key = f.read() # 2. Create verifier config = DidWbaVerifierConfig( jwt_private_key=jwt_private_key, jwt_public_key=jwt_public_key, jwt_algorithm="RS256", access_token_expire_minutes=60, ) verifier = DidWbaVerifier(config) # 3. Create FastAPI app and register middleware app = FastAPI() # Paths that bypass authentication exempt_paths = ["/health", "/docs", "/openapi.json"] @app.middleware("http") async def did_wba_auth(request: Request, call_next): return await auth_middleware( request, call_next, verifier, exempt_paths=exempt_paths ) # 4. Define routes @app.get("/health") async def health(): """Exempt endpoint, no authentication required.""" return {"status": "healthy"} @app.get("/api/protected") async def protected(request: Request): """Protected endpoint, requires DID authentication.""" did = request.state.did # DID is auto-injected after authentication return {"message": "Authentication successful", "did": did} ``` -------------------------------- ### Install ANP TypeScript SDK via npm Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/README.md Install the @awiki/anp-typescript-sdk package from the AWiki scope. Requires Node 20+. ```bash npm install @awiki/anp-typescript-sdk ``` -------------------------------- ### Run advanced_server with uvicorn Source: https://github.com/agent-network-protocol/anp/blob/master/anp/openanp/README.md Commands to run the advanced server example, either the standard app or the custom ad.json variant, on port 8000. ```bash # Standard app uvicorn examples.python.openanp_examples.advanced_server:app --port 8000 # App with custom ad.json uvicorn examples.python.openanp_examples.advanced_server:app_custom --port 8000 ``` -------------------------------- ### Expected output of complete authentication Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/did_wba_examples/README.md Shows the expected output lines from the complete authentication example, including the created DID, proof type, authentication methods, and token caching status. ```text Created e1 DID: did:wba:example.com:agents:alice:e1_ DID document proof: eddsa-jcs-2022 Request authentication: http_signatures Issued and cached Bearer token: True Bearer token authentication: bearer Authenticated DID: did:wba:example.com:agents:alice:e1_ ``` -------------------------------- ### Run TypeScript DID WBA HTTP server and client Source: https://github.com/agent-network-protocol/anp/blob/master/docs/examples.md Run the DID WBA HTTP examples demonstrating the Node.js server/client flow. Terminal 1 runs the server, Terminal 2 runs the client. ```bash # Terminal 1 cd typescript/ts_sdk npm run build node examples/did-wba-http-server.mjs ``` ```bash # Terminal 2 cd typescript/ts_sdk node examples/did-wba-http-client.mjs ``` -------------------------------- ### Run merchant server Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/ap2_examples/README.md Command to start the merchant server, which binds to your local IP by default. Optional flags include --host 0.0.0.0 and --port 8889. ```bash uv run python examples/python/ap2_examples/merchant_server.py ``` -------------------------------- ### Install ANP Go SDK Source: https://github.com/agent-network-protocol/anp/blob/master/golang/README.md Adds the ANP Go SDK module to your Go project. Requires Go 1.22+ and pure Go (no cgo). ```bash go get github.com/agent-network-protocol/anp/golang ``` -------------------------------- ### Minimal FastANP example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/fastanp/README.md Initialize FastAPI and FastANP plugin, define an ad.json route, register an interface method, and run the server. Disables auth for demo. ```python from fastapi import FastAPI from anp.fastanp import FastANP, Context from anp.authentication.did_wba_verifier import DidWbaVerifierConfig # Initialize FastAPI app = FastAPI() # Initialize FastANP plugin (without auth) anp = FastANP( app=app, name="Simple Agent", description="A simple ANP agent", base_url="https://example.com", did="did:wba:example.com:agent:simple", enable_auth_middleware=False # Disable auth for demo ) # Define ad.json route (user has full control) @app.get("/ad.json") def get_agent_description(): ad = anp.get_common_header() ad["interfaces"] = [ anp.interfaces[hello].link_summary ] return ad # Register interface method @anp.interface("/info/hello.json", description="Say hello") def hello(name: str) -> dict: """ Greet someone by name. Args: name: The name to greet """ return {"message": f"Hello, {name}!"} # Run server if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) ``` -------------------------------- ### Context Injection example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/openanp/README.md Shows how to use the Context parameter for session management, caller identification, and raw request access. The context parameter is automatically injected and excluded from OpenRPC schemas. ```python from anp.openanp import Context @interface async def method(self, param: str, ctx: Context) -> dict: # Session management (based on caller's DID) ctx.session.set("key", "value") value = ctx.session.get("key") # Caller identification print(f"Called by: {ctx.did}") # Access raw request headers = ctx.request.headers return {"user": ctx.did} ``` -------------------------------- ### P2P: Both Client and Server with RemoteAgent.discover Source: https://github.com/agent-network-protocol/anp/blob/master/anp/openanp/README.md Shows an agent that acts as both server and client, using @anp_agent to expose methods and RemoteAgent.discover to call another agent. Includes session tracking and authentication setup for client calls. ```python from anp.openanp import anp_agent, interface, AgentConfig, Context, RemoteAgent from anp.authentication import DIDWbaAuthHeader @anp_agent(AgentConfig( name="Travel Agent", did="did:wba:example.com:travel", prefix="/travel", )) class TravelAgent: def __init__(self, auth: DIDWbaAuthHeader): self.auth = auth @interface async def plan_trip(self, destination: str, ctx: Context) -> dict: """Plan a trip - I'm both server and client.""" # Track in session ctx.session.set("destination", destination) # Discover and call hotel agent (client mode) hotel = await RemoteAgent.discover( "http://localhost:8000/hotel/ad.json", self.auth ) hotels = await hotel.search(query=destination) return { "destination": destination, "hotels": hotels, "planner_did": ctx.did, } # Create with auth for client calls auth = DIDWbaAuthHeader(...) travel_agent = TravelAgent(auth) app.include_router(travel_agent.router()) ``` -------------------------------- ### call_jsonrpc usage example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/API_PROPOSAL.md Example of calling call_jsonrpc to invoke a method and printing the result on success. ```python result = await client.call_jsonrpc( "http://localhost:8000/rpc", "calculate", {"expression": "2 + 3"} ) if result["success"]: print(result["result"]) ``` -------------------------------- ### Sync environment with uv Source: https://github.com/agent-network-protocol/anp/blob/master/CLAUDE.md Sets up the Python environment using uv. Use --extra api to include FastAPI/OpenAI dependencies, --extra dev for testing tools, or combine them with --extra api,dev for all optional dependencies. ```bash uv sync # Sync environment from pyproject.toml uv sync --extra api # Install with FastAPI/OpenAI dependencies uv sync --extra dev # Install with dev/testing dependencies uv sync --extra api,dev # Install all optional dependencies ``` -------------------------------- ### Build wheel with uv Source: https://github.com/agent-network-protocol/anp/blob/master/CLAUDE.md Builds a wheel distribution for the package using uv. ```bash uv build --wheel # Build wheel for distribution ``` -------------------------------- ### 创建 DID 文档和私钥 (create_did_wba_document) Source: https://github.com/agent-network-protocol/anp/blob/master/docs/did/getting_started.md 使用 create_did_wba_document 函数生成 DID 文档和密钥对。默认创建路径型 DID,格式为 did:wba:example.com:user:alice:e1_。返回的 keys 字典包含每个 method_fragment 对应的 (私钥字节, 公钥字节) 元组。 ```python from anp.authentication import create_did_wba_document # Create DID document and key pair did_document, keys = create_did_wba_document( hostname="example.com", # Hostname path_segments=["user", "alice"], # Optional path segments agent_description_url="https://example.com/agents/alice/description.json" # Optional agent description URL ) # did_document is the generated DID document # keys is a dictionary containing private and public keys in format {method_fragment: (private_key_bytes, public_key_bytes)} ``` -------------------------------- ### Install, typecheck, test, and build the TypeScript SDK Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/README.md Run these commands in order to set up the SDK, verify types, run the test suite, and build the package. Note that `npm publish` does not run tests by default; run `npm test` explicitly when tests are requested. ```bash npm install npm run typecheck npm test npm run build ``` -------------------------------- ### call_jsonrpc example Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/README.md Example of using call_jsonrpc to make a JSON-RPC call. The method is awaited and the result is checked for success before printing. ```python result = await client.call_jsonrpc( "https://example.com/rpc", "search", {"query": "Tokyo"} ) if result["success"]: print(result["result"]) ``` -------------------------------- ### Install FastANP with uv or pip Source: https://github.com/agent-network-protocol/anp/blob/master/anp/fastanp/README.md Install the anp package with optional API dependencies using either uv or pip. ```bash # Using uv uv sync --extra api ``` ```bash # Or using pip pip install -e ".[api]" ``` -------------------------------- ### Generate DID document with tool Source: https://github.com/agent-network-protocol/anp/blob/master/CLAUDE.md Generates a DID document using the provided tool. Pass a DID as the first argument and optionally an --agent-description-url. ```bash # DID document generation tool uv run python tools/did_generater/generate_did_doc.py [--agent-description-url URL] ``` -------------------------------- ### Generated ad.json Infomations Source: https://github.com/agent-network-protocol/anp/blob/master/anp/openanp/README.md Example of the generated ad.json structure for Information definitions, showing URL and content modes. ```json { "Infomations": [ { "type": "Product", "description": "Room catalog", "url": "https://example.com/hotel/products/rooms.json" }, { "type": "Contact", "description": "Contact info", "content": {"phone": "+1-234-567"} } ] } ``` -------------------------------- ### Client: Call Remote Agents with RemoteAgent.discover Source: https://github.com/agent-network-protocol/anp/blob/master/anp/openanp/README.md Shows how to set up DID-WBA authentication, discover a remote agent from its ad.json, inspect available methods, and call them dynamically or explicitly. Also demonstrates getting OpenAI tools format for LLM integration. ```python from anp.openanp import RemoteAgent from anp.authentication import DIDWbaAuthHeader # Setup authentication (DID-WBA) auth = DIDWbaAuthHeader( did_document_path="/path/to/did-doc.json", private_key_path="/path/to/private-key.pem", ) # Discover agent from ad.json (fetches interface.json automatically) agent = await RemoteAgent.discover("https://hotel.example.com/ad.json", auth) # Inspect available methods print(f"Agent: {agent.name}") print(f"Methods: {agent.method_names}") # ('search', 'book') # Call methods - dynamic access result = await agent.search(query="Tokyo") # Or explicit call result = await agent.call("search", query="Tokyo") # Get OpenAI tools format (for LLM integration) tools = agent.tools ``` -------------------------------- ### Run shopper client Source: https://github.com/agent-network-protocol/anp/blob/master/examples/python/ap2_examples/README.md Command to run the shopper client, pointing it at the merchant URL. Both arguments default to the demo DID/document shipped in docs/did_public/, so they can usually be omitted when testing locally. ```bash uv run python examples/python/ap2_examples/shopper_client.py \ --merchant-url http://: \ --merchant-did did:wba:didhost.cc:public ``` -------------------------------- ### Generated ad.json structure for interfaces Source: https://github.com/agent-network-protocol/anp/blob/master/anp/openanp/README.md Example of the generated ad.json structure showing how content and link mode interfaces are listed. ```json { "interfaces": [ { "type": "StructuredInterface", "protocol": "openrpc", "url": "https://example.com/hotel/interface.json", "description": "Hotel Service JSON-RPC interface" }, { "type": "StructuredInterface", "protocol": "openrpc", "url": "https://example.com/hotel/interface/book.json", "description": "Book a hotel room" } ] } ``` -------------------------------- ### Run server and client in separate terminals Source: https://github.com/agent-network-protocol/anp/blob/master/README.md Full runnable pair: start the server in one terminal and the client in another. ```bash # Terminal 1 uvicorn examples.python.openanp_examples.minimal_server:app --port 8000 # Terminal 2 uv run python examples/python/openanp_examples/minimal_client.py ``` -------------------------------- ### Common local development commands Source: https://github.com/agent-network-protocol/anp/blob/master/README.md Run these commands in the repository root or the language-specific directory to test and build each SDK. Python commands use uv; Go, Rust, Dart, TypeScript, and Java have their own toolchains. Some examples require network access or .env configuration. ```bash # Python uv sync uv sync --extra api # OpenANP / FastAPI examples uv sync --extra dev # pytest and development tools uv run pytest uv build --wheel # Go cd golang go test ./... # Rust cd rust cargo test # Dart cd dart dart pub get dart analyze dart test # TypeScript preview workspace cd typescript/ts_sdk npm install npm run typecheck npm test npm run build # Java local workspace cd java mvn test ``` -------------------------------- ### Run Python Client to TypeScript Server Interop Source: https://github.com/agent-network-protocol/anp/blob/master/docs/examples.md Starts the TypeScript HTTP server and runs the Python client to authenticate. ```bash node examples/did-wba-http-server.mjs uv run python typescript/ts_sdk/examples/python_to_ts_did_wba_client.py ``` -------------------------------- ### get_tool_interface_info(tool_name: str) → Optional[Dict] Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/README.md Gets metadata for a specific tool. ```APIDOC ## get_tool_interface_info(tool_name: str) → Optional[Dict] ### Description Gets metadata for a specific tool. ### Parameters - `tool_name` (str) - Required - Name of the tool ### Returns ```python { "tool_name": str, "method_name": str, "servers": List[Dict], "interface_data": Dict } ``` ``` -------------------------------- ### Verify WNS binding with BindingVerificationOptions Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/docs/configuration.md Use verifyBinding() with BindingVerificationOptions to verify a WNS binding. The example passes a didDocument and resolution options. ```typescript const result = await verifyBinding('alice.example.com', { didDocument, resolutionOptions: { baseUrlOverride: 'http://127.0.0.1:8080' }, }); ``` -------------------------------- ### Typical Workflow Steps Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/README.md Outlines the typical workflow for using ANPCrawler: initialize with DID document and private key, fetch agent description, discover tools, execute tools, and process results. ```text 1. Initialize ANPCrawler └─ Provide DID document and private key for authentication 2. Fetch Agent Description (ad.json) └─ crawler.fetch_text(url) └─ Returns content and interface list 3. Discover Available Tools └─ crawler.list_available_tools() └─ Returns tool names 4. Execute Tools └─ crawler.execute_tool_call(name, args) └─ Or: crawler.execute_json_rpc(endpoint, method, params) 5. Process Results └─ Handle success/error responses ``` -------------------------------- ### JSON-RPC response Source: https://github.com/agent-network-protocol/anp/blob/master/anp/fastanp/README.md Example response from the /rpc endpoint after calling the hello method. ```json { "jsonrpc": "2.0", "result": { "message": "Hello, World!" }, "id": 1 } ``` -------------------------------- ### Server: Expose Methods with Context using @anp_agent Source: https://github.com/agent-network-protocol/anp/blob/master/anp/openanp/README.md Demonstrates creating a FastAPI-based agent with @anp_agent decorator, defining static Information objects, and exposing methods via @interface. Shows content mode (default) and link mode, plus automatic endpoint generation. ```python from fastapi import FastAPI from anp.openanp import anp_agent, interface, AgentConfig, Context, Information @anp_agent(AgentConfig( name="Hotel Service", did="did:wba:example.com:hotel", prefix="/hotel", description="Hotel booking service", )) class HotelAgent: # Static Information definitions informations = [ Information( type="VideoObject", description="Hotel tour", url="https://cdn.example.com/tour.mp4", ), Information( type="Contact", description="Hotel contact info", mode="content", content={"phone": "+1-234-567"}, ), ] @interface # Default: content mode (embedded in interface.json) async def search(self, query: str) -> dict: """Search for hotels.""" return {"results": [{"name": "Tokyo Hotel", "price": 100}]} @interface # With Context injection async def search_with_session(self, query: str, ctx: Context) -> dict: """Search with session tracking.""" # ctx.did - caller's DID # ctx.session - session for this DID # ctx.request - FastAPI Request ctx.session.set("last_query", query) return {"results": [...], "user": ctx.did} @interface(mode="link") # Link mode: separate interface file async def book(self, hotel_id: str, date: str) -> dict: """Book a hotel room.""" return {"booking_id": "12345", "status": "confirmed"} app = FastAPI() app.include_router(HotelAgent.router()) # Automatically generates: # - GET /hotel/ad.json (with Informations) # - GET /hotel/interface.json (content mode methods) # - GET /hotel/interface/book.json (link mode methods) # - POST /hotel/rpc (JSON-RPC 2.0) ``` -------------------------------- ### PaymentMandate with ES256K Source: https://github.com/agent-network-protocol/anp/blob/master/docs/ap2/ES256K_SUPPORT.md Create a PaymentMandateBuilder with algorithm='ES256K', build a PaymentMandate, and verify it with PaymentMandateVerifier. Assumes the same key pair generation as the CartMandate example. ```python from anp.ap2.payment_mandate import PaymentMandateBuilder, PaymentMandateVerifier from anp.ap2.models import PaymentMandateContents, ... # Generate user's ES256K key pair (same as above) # ... # Create builder with ES256K algorithm builder = PaymentMandateBuilder( user_private_key=private_pem, user_did="did:wba:didhost.cc:shopper", user_kid="shopper-es256k-key-001", algorithm="ES256K", # Specify ES256K algorithm merchant_did="did:wba:didhost.cc:merchant" ) # Build PaymentMandate payment_mandate = builder.build( payment_mandate_contents=payment_contents, cart_hash=cart_hash, extensions=["anp.ap2.qr.v1", "anp.human_presence.v1"] ) # Verify PaymentMandate verifier = PaymentMandateVerifier( user_public_key=public_pem, algorithm="ES256K" # Specify ES256K algorithm ) payload = verifier.verify( payment_mandate=payment_mandate, expected_cart_hash=cart_hash, expected_aud="did:wba:didhost.cc:merchant" ) ``` -------------------------------- ### Before: Multiple Methods Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/API_IMPROVEMENTS.md Shows the old API with separate methods get_agent_description() and get_information() before the unified fetch() method was introduced. ```python # Fetch agent description agent_result = await client.get_agent_description(ad_url) if not agent_result["success"]: print(f"Failed: {agent_result['error']}") return agent_data = agent_result["data"] # Fetch information endpoint hello_result = await client.get_information(f"{server_url}/info/hello.json") if hello_result["success"]: print(hello_result["data"]) ``` -------------------------------- ### call_jsonrpc() Usage Source: https://github.com/agent-network-protocol/anp/blob/master/anp/anp_crawler/API_IMPROVEMENTS.md Example of using the dedicated call_jsonrpc() method for JSON-RPC calls, specifying server URL, method name, and parameters. ```python result = await client.call_jsonrpc( server_url="http://localhost:8000/rpc", method="calculate", params={"expression": "2 + 3"} ) ``` -------------------------------- ### Run full Go SDK validation Source: https://github.com/agent-network-protocol/anp/blob/master/golang/docs/direct_e2ee-guide.md Runs the full Go SDK validation suite, including unit and integration tests. ```bash go test ./... ``` -------------------------------- ### Resolve WNS handle with ResolveHandleOptions Source: https://github.com/agent-network-protocol/anp/blob/master/typescript/ts_sdk/docs/configuration.md Use resolveHandle() with ResolveHandleOptions to resolve a WNS handle. The example overrides the base URL and sets a timeout. ```typescript const result = await resolveHandle('alice.example.com', { baseUrlOverride: 'http://127.0.0.1:8080', timeoutSeconds: 5, }); ```