### Setup Python Environment with UV Source: https://github.com/a2aproject/a2a-dotnet/blob/main/samples/AgentServer/README.md Set up a Python virtual environment using 'uv' and install project dependencies. Ensure the virtual environment is activated before proceeding. ```bash # Create virtual environment uv venv # Activate virtual environment # On Windows: .venv\Scripts\activate # On macOS/Linux: source .venv/bin/activate # Install dependencies uv pip install -e . ``` -------------------------------- ### ExecuteAsync Example: Simple Echo Response Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/agent-handler.md A basic example demonstrating how to implement ExecuteAsync for a simple echo response using MessageResponder. ```csharp public async Task ExecuteAsync( RequestContext context, AgentEventQueue eventQueue, CancellationToken cancellationToken) { var responder = new MessageResponder(eventQueue, context.ContextId); await responder.ReplyAsync($"Echo: {context.UserText}", cancellationToken); } ``` -------------------------------- ### ExecuteAsync Example: Task-Based Response Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/agent-handler.md An example showing how to implement ExecuteAsync for task-based responses, including submitting, starting, updating, and completing a task. ```csharp public async Task ExecuteAsync( RequestContext context, AgentEventQueue eventQueue, CancellationToken cancellationToken) { var updater = new TaskUpdater(eventQueue, context.TaskId, context.ContextId); // Emit the task as submitted await updater.SubmitAsync(cancellationToken: cancellationToken); // Start work await updater.StartWorkAsync(message: new Message { Role = Role.Agent, Parts = [Part.FromText("Processing your request...")] }, cancellationToken: cancellationToken); // Do work... await Task.Delay(1000, cancellationToken); // Add an artifact await updater.AddArtifactAsync( parts: [Part.FromText("Result data")], name: "output.txt", cancellationToken: cancellationToken); // Complete the task await updater.CompleteAsync( message: new Message { Role = Role.Agent, Parts = [Part.FromText("Task completed successfully")] }, cancellationToken: cancellationToken); } ``` -------------------------------- ### Install ASP.NET Core Extensions Source: https://github.com/a2aproject/a2a-dotnet/blob/main/README.md Install the ASP.NET Core integration package for the A2A SDK. This enables hosting A2A agents within ASP.NET Core applications. ```bash dotnet add package A2A.AspNetCore ``` -------------------------------- ### Example curl for sending a message Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt This example demonstrates how to send a message using curl. It shows the necessary headers and the JSON payload structure. ```bash curl -X POST https://api.example.com/v1/messages \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "recipient": "agent_id_or_user_id", "content": { "type": "text", "text": "Hello from curl!" } }' ``` -------------------------------- ### StartWorkAsync Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/task-updater.md Transitions the task to the 'Working' state. Use this to indicate that processing has begun, optionally with a status message. ```csharp await updater.StartWorkAsync( message: new Message { Role = Role.Agent, Parts = [Part.FromText("Processing your request...")] }, cancellationToken: cancellationToken); ``` -------------------------------- ### Example curl for getting a task status Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt This example shows how to retrieve the status of a task using curl. It requires the task ID and appropriate authorization. ```bash curl -X GET https://api.example.com/v1/tasks/task_id_123 \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Complete ASP.NET Core A2A Agent Setup Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/aspnetcore-extensions.md This snippet demonstrates a complete setup for an A2A agent within an ASP.NET Core application. It includes defining the agent card, registering A2A services, mapping A2A endpoints, and implementing a basic agent handler. ```csharp using A2A; using A2A.AspNetCore; var builder = WebApplication.CreateBuilder(args); // Define agent card var agentCard = new AgentCard { Name = "Research Agent", Description = "Performs research and analysis", Version = "1.0.0", Url = "http://localhost:5000/research", SupportedInterfaces = [new AgentInterface { Url = "http://localhost:5000/research", ProtocolBinding = "JSONRPC", ProtocolVersion = "1.0" }], DefaultInputModes = ["text/plain"], DefaultOutputModes = ["text/plain"], Capabilities = new AgentCapabilities { Streaming = true }, Skills = [new AgentSkill { Id = "research", Name = "Research", Description = "Research topics" }] }; // Register services builder.Services.AddA2AAgent(agentCard, options => { options.AutoAppendHistory = true; }); var app = builder.Build(); // Map both JSON-RPC and REST endpoints app.MapA2A("/rpc"); app.MapHttpA2A(app.Services.GetRequiredService(), ""); app.MapWellKnownAgentCard(agentCard); app.Run(); // Agent implementation public class ResearchAgent : IAgentHandler { public async Task ExecuteAsync( RequestContext context, AgentEventQueue eventQueue, CancellationToken cancellationToken) { var updater = new TaskUpdater(eventQueue, context.TaskId, context.ContextId); await updater.SubmitAsync(cancellationToken: cancellationToken); await updater.StartWorkAsync(cancellationToken: cancellationToken); // Do research... await Task.Delay(2000, cancellationToken); await updater.CompleteAsync( message: new Message { Role = Role.Agent, Parts = [Part.FromText("Research complete")] }, cancellationToken: cancellationToken); } public Task CancelAsync(RequestContext context, AgentEventQueue eventQueue, CancellationToken cancellationToken) { var updater = new TaskUpdater(eventQueue, context.TaskId, context.ContextId); return updater.CancelAsync(cancellationToken: cancellationToken); } } ``` -------------------------------- ### Example appsettings.json for A2A Configuration Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/configuration.md Illustrates how to define A2A specific settings and logging levels within the appsettings.json file. ```json { "A2A": { "AgentName": "Research Agent", "AgentUrl": "http://localhost:5000/research", "MaxHistoryLength": 50, "AutoAppendHistory": true }, "Logging": { "LogLevel": { "Default": "Information", "A2A": "Debug" } } } ``` -------------------------------- ### Install Core A2A Library Source: https://github.com/a2aproject/a2a-dotnet/blob/main/README.md Install the core A2A library using the .NET CLI. This package contains the fundamental A2A protocol implementation. ```bash dotnet add package A2A ``` -------------------------------- ### SubmitAsync Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/task-updater.md Emits the initial task with a 'Submitted' status. Call this method to begin the task lifecycle. ```csharp var updater = new TaskUpdater(eventQueue, taskId, contextId); await updater.SubmitAsync(cancellationToken: cancellationToken); ``` -------------------------------- ### Sample Interaction Source: https://github.com/a2aproject/a2a-dotnet/blob/main/samples/SemanticKernelAgent/README.md This is an example of the interaction between the client and the Semantic Kernel Agent. It shows a user query and the agent's response. ```text You: Hi, I live in Korea. I want to travel to Dublin for a week and visit the sites. What should I visit and how much money will I need? Debug: Started activity 00-21cbaf6cba101313a71ff23d967aab33-0688a522a002a0b6-01 of kind Client TravelPlanner: That’s a wonderful trip! Dublin is full of history, culture, and fun experiences. Here’s a recommended one-week itinerary with top sites and a budget estimate for your visit from Korea. ``` -------------------------------- ### Run AgentServer with Launch Profiles Source: https://github.com/a2aproject/a2a-dotnet/blob/main/samples/AgentServer/README.md Use `dotnet run` with launch profiles to start the AgentServer with specific agent configurations. Ensure you are in the AgentServer directory. ```bash cd samples/AgentServer dotnet run --launch-profile echo-agent dotnet run --launch-profile echotasks-agent dotnet run --launch-profile researcher-agent dotnet run --launch-profile speccompliance-agent ``` -------------------------------- ### Simple Echo Agent Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/message-responder.md Demonstrates a basic agent that echoes user input using MessageResponder. It initializes the responder and sends a text reply. ```csharp public class EchoAgent : IAgentHandler { public async Task ExecuteAsync( RequestContext context, AgentEventQueue eventQueue, CancellationToken cancellationToken) { var responder = new MessageResponder(eventQueue, context.ContextId); await responder.ReplyAsync($"You said: {context.UserText}", cancellationToken); } public Task CancelAsync(RequestContext context, AgentEventQueue eventQueue, CancellationToken cancellationToken) { // No cleanup needed for stateless agent return Task.CompletedTask; } } ``` -------------------------------- ### CancelAsync Example: Custom Cleanup Logic Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/agent-handler.md An example demonstrating how to override CancelAsync to implement custom cleanup logic before emitting a cancellation event. ```csharp public async Task CancelAsync( RequestContext context, AgentEventQueue eventQueue, CancellationToken cancellationToken) { // Custom cleanup: abort external API calls, release resources, etc. await AbortExternalWorkAsync(context.TaskId, cancellationToken); // Emit cancellation event var updater = new TaskUpdater(eventQueue, context.TaskId, context.ContextId); await updater.CancelAsync(cancellationToken: cancellationToken); } ``` -------------------------------- ### Example Usage of A2ACardResolver Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/a2a-card-resolver.md Demonstrates how to instantiate A2ACardResolver, retrieve an agent card, and use its information to create an A2AClient. Handles potential exceptions during the process. ```csharp var resolver = new A2ACardResolver(new Uri("http://localhost:5000/")); var agentCard = await resolver.GetAgentCardAsync(); Console.WriteLine($"Agent: {agentCard.Name}"); Console.WriteLine($"Version: {agentCard.Version}"); Console.WriteLine($"Capabilities: Streaming={agentCard.Capabilities.Streaming}"); // Create client using the discovered endpoint var client = new A2AClient(new Uri(agentCard.SupportedInterfaces[0].Url)); ``` -------------------------------- ### Clone Repository Source: https://github.com/a2aproject/a2a-dotnet/blob/main/samples/SemanticKernelAgent/README.md Clone the a2a-dotnet repository to your local machine. Ensure you have Git installed. ```bash git clone https://github.com/a2aproject/a2a-dotnet cd a2a-dotnet ``` -------------------------------- ### Migrate Simple Message-Only Agent (v0.3) Source: https://github.com/a2aproject/a2a-dotnet/blob/main/docs/taskmanager-migration-guide.md Example of a v0.3 agent using OnMessageReceived for direct responses. ```csharp taskManager.OnMessageReceived = async (msgParams, ct) => { var text = msgParams.Message.Parts.OfType().First().Text; return new AgentMessage { Role = MessageRole.Agent, MessageId = Guid.NewGuid().ToString(), ContextId = msgParams.Message.ContextId, Parts = [new TextPart { Text = $"Echo: {text}" }] }; }; ``` -------------------------------- ### Migrate Task-Based Agent (v0.3) Source: https://github.com/a2aproject/a2a-dotnet/blob/main/docs/taskmanager-migration-guide.md Example of a v0.3 agent handling task lifecycle events like creation and cancellation. ```csharp // Agent received callbacks at different lifecycle stages taskManager.OnTaskCreated = async (task, ct) => { // Start processing await taskManager.UpdateStatusAsync(task.Id, TaskState.Working, null, false, ct); // Do work... var result = await DoWorkAsync(task, ct); // Return artifact await taskManager.ReturnArtifactAsync(task.Id, new Artifact { ArtifactId = "result", Parts = [new TextPart { Text = result }] }); // Mark complete await taskManager.UpdateStatusAsync(task.Id, TaskState.Completed, null, true, ct); }; taskManager.OnTaskCancelled = async (task, ct) => { // Cleanup... }; ``` -------------------------------- ### REST Response Example (Task) Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/endpoints.md A sample JSON response when the message:send operation returns a task. ```json { "task": { "id": "task-123", "contextId": "ctx-123", "status": { "state": "TASK_STATE_SUBMITTED", "timestamp": "2026-06-09T12:34:56Z" } } } ``` -------------------------------- ### Example Usage of RequireAuthAsync Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/task-updater.md Demonstrates how to call the RequireAuthAsync method with a specific message and cancellation token to initiate an OAuth authentication requirement. ```csharp await updater.RequireAuthAsync( message: new Message { Role = Role.Agent, Parts = [Part.FromText("OAuth authentication required")] }, cancellationToken: cancellationToken); ``` -------------------------------- ### REST Response Example (Message) Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/endpoints.md A sample JSON response when the message:send operation returns a direct message. ```json { "message": { "role": "ROLE_AGENT", "parts": [{"text": "Hello user!"}], "messageId": "msg-456", "contextId": "ctx-123" } } ``` -------------------------------- ### Multi-Part Response Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/message-responder.md Shows how to construct and send a multi-part response using MessageResponder. It creates a list of Part objects, including text and data, and then sends them. ```csharp public async Task ExecuteAsync( RequestContext context, AgentEventQueue eventQueue, CancellationToken cancellationToken) { var responder = new MessageResponder(eventQueue, context.ContextId); var parts = new List { Part.FromText("Analysis complete:"), Part.FromData(JsonDocument.Parse("{"result": 42}").RootElement) }; await responder.ReplyAsync(parts, cancellationToken); } ``` -------------------------------- ### REST POST Request for message:send Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/endpoints.md Example of sending a message using the REST binding. This POST request includes the message and configuration details. ```bash curl -X POST http://localhost:5000/message:send \ -H "Content-Type: application/json" \ -d '{ "message": { "role": "ROLE_USER", "parts": [{"text": "Hello agent!"}], "messageId": "msg-123" }, "configuration": { "acceptedOutputModes": ["text/plain"] } }' ``` -------------------------------- ### Register InMemoryTaskStore with Dependency Injection Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/itask-store.md Example of how to register the InMemoryTaskStore as a singleton service in an ASP.NET Core application's dependency injection container. ```csharp var taskStore = new InMemoryTaskStore(); builder.Services.AddSingleton(taskStore); ``` -------------------------------- ### Subscribe to Task Updates Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/README.md Subscribe to live updates for a specific task using the A2AClient. This example shows how to listen for task completion. ```csharp var client = new A2AClient(agentUrl); // Send message that returns a task var response = await client.SendMessageAsync(new SendMessageRequest { Message = new Message { /* ... */ } }); var taskId = response.Task?.Id; // Subscribe to live updates await foreach (var update in client.SubscribeToTaskAsync( new SubscribeToTaskRequest { Id = taskId })) { if (update.StatusUpdate?.Status.State == TaskState.Completed) { Console.WriteLine("Task complete!"); break; } } ``` -------------------------------- ### ITaskStore Interface Methods Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/MANIFEST.md The ITaskStore interface defines methods for persisting and retrieving task information, with built-in and database implementation examples. ```APIDOC ## ITaskStore Interface Methods ### Description Persistence interface for managing task data. ### Methods - GetTaskAsync(string taskId) - SaveTaskAsync(TaskData task) - DeleteTaskAsync(string taskId) - ListTasksAsync(ListTasksRequest request) ### Schemas - `ListTasksRequest` - `ListTasksResponse` ### Implementations - `InMemoryTaskStore` - Database implementation example (Details on thread safety and consistency are in itask-store.md) ``` -------------------------------- ### A2AServer DisposeAsync Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/a2a-server.md Demonstrates the correct usage of the DisposeAsync method to ensure proper cleanup of the A2AServer instance. It is crucial to call DisposeAsync in a finally block to guarantee resource release. ```csharp var server = new A2AServer(handler, taskStore, notifier, logger); try { // Use server } finally { await server.DisposeAsync(); } ``` -------------------------------- ### Response with Metadata Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/message-responder.md Illustrates sending a response with custom metadata using MessageResponder. A dictionary of key-value pairs is created and passed to the ReplyAsync method. ```csharp public async Task ExecuteAsync( RequestContext context, AgentEventQueue eventQueue, CancellationToken cancellationToken) { var responder = new MessageResponder(eventQueue, context.ContextId); var metadata = new Dictionary { { "processingTime", JsonDocument.Parse("1234").RootElement }, { "model", JsonDocument.Parse("\"gpt-4\"").RootElement } }; await responder.ReplyAsync("Response with metadata", metadata, cancellationToken); } ``` -------------------------------- ### SubmitAsync Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/task-updater.md Emits the initial task with a 'Submitted' status. This method is used to start the task lifecycle by sending the initial submission event. ```APIDOC ## SubmitAsync ### Description Emit the initial task with `Submitted` status. This method is used to start the task lifecycle by sending the initial submission event. ### Method `public ValueTask SubmitAsync(Dictionary? metadata = null, CancellationToken cancellationToken = default)` ### Parameters #### Query Parameters - **metadata** (Dictionary?) - No - Optional metadata to attach to the task. - **cancellationToken** (CancellationToken) - No - Cancellation token. ### Returns `ValueTask` — Completes when the event is enqueued. ### Example ```csharp var updater = new TaskUpdater(eventQueue, taskId, contextId); await updater.SubmitAsync(cancellationToken: cancellationToken); ``` ``` -------------------------------- ### SendMessageAsync Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/a2a-server.md Demonstrates how to send a message using SendMessageAsync and receive a response. This method handles message requests and returns a response containing either a direct message or a task reference. ```csharp var server = new A2AServer( agentHandler, taskStore, notifier, logger); var response = await server.SendMessageAsync(new SendMessageRequest { Message = new Message { MessageId = Guid.NewGuid().ToString("N"), Role = Role.User, Parts = [Part.FromText("Hello")] } }); ``` -------------------------------- ### Build a Task-Based Agent Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/README.md Implement an agent that handles tasks, including starting, updating, adding artifacts, and completing tasks. This requires implementing the IAgentHandler interface. ```csharp public class ResearchAgent : IAgentHandler { public async Task ExecuteAsync( RequestContext context, AgentEventQueue eventQueue, CancellationToken cancellationToken) { var updater = new TaskUpdater(eventQueue, context.TaskId, context.ContextId); // Emit task lifecycle await updater.SubmitAsync(cancellationToken: cancellationToken); await updater.StartWorkAsync(cancellationToken: cancellationToken); // Do work var result = await DoResearchAsync(context.UserText, cancellationToken); // Add artifact await updater.AddArtifactAsync( [Part.FromText(result)], name: "research-results.txt", cancellationToken: cancellationToken); // Complete await updater.CompleteAsync(cancellationToken: cancellationToken); } public async Task CancelAsync( RequestContext context, AgentEventQueue eventQueue, CancellationToken cancellationToken) { var updater = new TaskUpdater(eventQueue, context.TaskId, context.ContextId); await updater.CancelAsync(cancellationToken: cancellationToken); } private Task DoResearchAsync(string topic, CancellationToken ct) => Task.FromResult($"Research on {topic}"); } ``` -------------------------------- ### Run Client with Arguments Source: https://github.com/a2aproject/a2a-dotnet/blob/main/samples/SemanticKernelAgent/README.md Launch the client application, providing the agent's URL and the desired planner name as arguments. The client interacts with the agent. ```bash cd samples\Client dotnet run http://localhost:5000 TravelPlanner ``` -------------------------------- ### Run Client Samples Source: https://github.com/a2aproject/a2a-dotnet/blob/main/README.md Command to navigate to the client samples directory and run the client sample application using the .NET CLI. ```bash cd samples/AgentClient dotnet run ``` -------------------------------- ### Run Semantic Kernel Agent Sample Source: https://github.com/a2aproject/a2a-dotnet/blob/main/samples/SemanticKernelAgent/README.md Launch the Semantic Kernel Agent sample server. This server will handle agent requests. ```bash cd samples\SemanticKernelAgent dotnet run ``` -------------------------------- ### DeleteTaskAsync Implementation Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/itask-store.md Provides an example implementation for deleting a task. This method is not called by the SDK and is intended for custom task pruning logic. ```csharp public async Task DeleteTaskAsync(string taskId, CancellationToken cancellationToken = default) { // Example: Delete from database await _database.DeleteAsync($"tasks/{taskId}", cancellationToken); } ``` -------------------------------- ### Build Solution Source: https://github.com/a2aproject/a2a-dotnet/blob/main/samples/SemanticKernelAgent/README.md Build the entire solution using the .NET CLI. This command compiles all projects in the solution. ```bash dotnet build ``` -------------------------------- ### v1 DI Registration and Endpoint Wiring Source: https://github.com/a2aproject/a2a-dotnet/blob/main/docs/taskmanager-migration-guide.md Demonstrates the v1 approach using `AddA2AAgent` for DI registration and `MapA2A` for endpoint mapping. ```csharp using A2A; using A2A.AspNetCore; var builder = WebApplication.CreateBuilder(args); // Register the agent, its card, and all A2A services via DI builder.Services.AddA2AAgent(EchoAgent.GetAgentCard("http://localhost:5000/echo")); var app = builder.Build(); // Map JSON-RPC endpoint app.MapA2A("/echo"); // Map well-known agent card for discovery var card = app.Services.GetRequiredService(); app.MapWellKnownAgentCard(card); app.Run(); ``` -------------------------------- ### MessageResponder ContextId Property Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/message-responder.md Gets the context ID that this MessageResponder instance operates on. ```csharp public string ContextId => contextId; ``` -------------------------------- ### TaskUpdater.TaskId Property Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/task-updater.md Gets the task ID associated with this TaskUpdater instance. This property is read-only. ```csharp public string TaskId => taskId; ``` -------------------------------- ### GetTaskAsync Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/itask-store.md Retrieves a task by its ID. Use this to fetch the current state of a specific task. ```csharp var task = await taskStore.GetTaskAsync("task-123"); if (task != null) { Console.WriteLine($"Task status: {task.Status.State}"); } ``` -------------------------------- ### Clone and Build Repository Source: https://github.com/a2aproject/a2a-dotnet/blob/main/README.md Standard commands to clone the A2A .NET repository and build the project using the .NET CLI. ```bash git clone https://github.com/a2aproject/a2a-dotnet.git cd a2a-dotnet dotnet build ``` -------------------------------- ### AddArtifactAsync Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/task-updater.md Adds an artifact, such as a file or result, to the task. This can be used for output files or intermediate data. ```csharp await updater.AddArtifactAsync( parts: [Part.FromText("Report content...")], name: "report.txt", description: "Generated report", cancellationToken: cancellationToken); ``` -------------------------------- ### List Tasks with Filters Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/endpoints.md Use this endpoint to list tasks, filtering by context ID, status, and pagination parameters. Ensure the server is running on the specified host and port. ```bash curl "http://localhost:5000/tasks?contextId=ctx-123&status=TASK_STATE_COMPLETED&pageSize=10" ``` -------------------------------- ### SaveTaskAsync Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/itask-store.md Persists the current state of an AgentTask. This method is called by the SDK after internal state mutations. ```csharp var task = new AgentTask { Id = "task-123", ContextId = "context-456", Status = new TaskStatus { State = TaskState.Completed, Timestamp = DateTimeOffset.UtcNow } }; await taskStore.SaveTaskAsync("task-123", task); ``` -------------------------------- ### Run AgentServer with Command Line Arguments Source: https://github.com/a2aproject/a2a-dotnet/blob/main/samples/AgentServer/README.md Execute the AgentServer directly using `dotnet run` and specify the agent type via command-line arguments. Navigate to the AgentServer directory first. ```bash cd samples/AgentServer dotnet run --agent echo dotnet run --agent echotasks dotnet run --agent researcher dotnet run --agent speccompliance ``` -------------------------------- ### A2AServer Constructor Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/a2a-server.md Initializes a new instance of the A2AServer class. Requires an agent handler, task store, notifier, and logger. Options are optional. ```csharp public class A2AServer : IA2ARequestHandler, IAsyncDisposable { public A2AServer( IAgentHandler handler, ITaskStore taskStore, ChannelEventNotifier notifier, ILogger logger, A2AServerOptions? options = null) { } } ``` -------------------------------- ### Build and Run A2A AgentClient Project Source: https://github.com/a2aproject/a2a-dotnet/blob/main/samples/AgentClient/README.md Commands to build and run the AgentClient project from the command line. ```bash cd samples/AgentClient dotnet build dotnet run ``` -------------------------------- ### Error Reference Format Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Outlines the structure for documenting error codes, including their values, trigger conditions, handling patterns, and examples. ```APIDOC ## Error Code: [ErrorCodeName] ### Code [ErrorCodeValue] ### Description [Description of the error] ### Trigger Conditions - [Condition 1] - [Condition 2] ### Handling Patterns - [Pattern 1 with example] - [Pattern 2 with example] ### Fallback and Retry Strategies - [Strategies for handling the error] ``` -------------------------------- ### StartWorkAsync Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/task-updater.md Transitions the task to the 'Working' state. This method can optionally include a status message to provide details about the ongoing work. ```APIDOC ## StartWorkAsync ### Description Transition task to `Working` state with an optional status message. This method can optionally include a status message to provide details about the ongoing work. ### Method `public ValueTask StartWorkAsync(Message? message = null, Dictionary? metadata = null, CancellationToken cancellationToken = default)` ### Parameters #### Query Parameters - **message** (Message?) - No - Optional message describing the current work. - **metadata** (Dictionary?) - No - Optional metadata. - **cancellationToken** (CancellationToken) - No - Cancellation token. ### Returns `ValueTask` — Completes when the event is enqueued. ### Example ```csharp await updater.StartWorkAsync( message: new Message { Role = Role.Agent, Parts = [Part.FromText("Processing your request...")] }, cancellationToken: cancellationToken); ``` ``` -------------------------------- ### /.well-known/agent-card.json (GET) Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/endpoints.md Standard endpoint for agent discovery. Returns the agent card, providing information about the agent's capabilities and configuration. ```APIDOC ## /.well-known/agent-card.json (GET) ### Description Standard endpoint for agent discovery. Returns the agent card. ### Method GET ### Endpoint /.well-known/agent-card.json ### Response #### Success Response (200) - **name** (string) - Agent name. - **description** (string) - Agent description. - **version** (string) - Agent version. - **url** (string) - Preferred endpoint URL. - **protocolVersion** (string) - A2A protocol version. - **capabilities** (AgentCapabilities) - Supported capabilities. - **skills** (AgentSkill[]) - Agent skills. - **defaultInputModes** (string[]) - Accepted input MIME types. - **defaultOutputModes** (string[]) - Produced output MIME types. - **supportedInterfaces** (AgentInterface[]) - Alternative endpoints/protocols. ### Request Example ```bash curl http://localhost:5000/.well-known/agent-card.json ``` ``` -------------------------------- ### Connect with A2AClient Source: https://github.com/a2aproject/a2a-dotnet/blob/main/README.md Demonstrates how to discover an agent's card and connect to it using A2AClient. It shows sending a message and handling the response, which could be a direct message or a task. ```csharp using A2A; // Discover agent var cardResolver = new A2ACardResolver(new Uri("http://localhost:5000/")); var agentCard = await cardResolver.GetAgentCardAsync(); // Create client using agent's endpoint var client = new A2AClient(new Uri(agentCard.SupportedInterfaces[0].Url)); // Send message var response = await client.SendMessageAsync(new SendMessageRequest { Message = new Message { MessageId = Guid.NewGuid().ToString("N"), Role = Role.User, Parts = [Part.FromText("Hello!")] } }); // Handle response switch (response.PayloadCase) { case SendMessageResponseCase.Message: Console.WriteLine(response.Message!.Parts[0].Text); break; case SendMessageResponseCase.Task: Console.WriteLine($"Task created: {response.Task!.Id}"); break; } ``` -------------------------------- ### v1 Agent Card Definition and Registration Source: https://github.com/a2aproject/a2a-dotnet/blob/main/docs/taskmanager-migration-guide.md Shows how to define an agent card and register it using `MapWellKnownAgentCard` in v1. ```csharp // Define the agent card (typically as a static method on the agent class) var card = new AgentCard { Name = "My Agent", Description = "Agent description", Version = "1.0.0", SupportedInterfaces = [new AgentInterface { Url = "http://localhost:5000/agent", ProtocolBinding = "JSONRPC", ProtocolVersion = "1.0" }], DefaultInputModes = ["text/plain"], DefaultOutputModes = ["text/plain"], Capabilities = new AgentCapabilities { Streaming = false }, Skills = [new AgentSkill { Id = "main", Name = "Main", Description = "...", Tags = ["main"] }], }; // Register at startup app.MapWellKnownAgentCard(card); ``` -------------------------------- ### Retrieve Task by ID (curl) Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/endpoints.md Fetch a specific task's details using its ID. This is the RESTful way to get task information. ```bash curl http://localhost:5000/tasks/task-123 ``` -------------------------------- ### GET /agent/authenticatedExtendedCard Source: https://github.com/a2aproject/a2a-dotnet/blob/main/tests/A2A.AspNetCore.UnitTests/specification.md Retrieves a detailed Agent Card after client authentication. This endpoint is only available if the Agent Card supports authenticated extended cards. ```APIDOC ## GET /agent/authenticatedExtendedCard ### Description Retrieves a potentially more detailed version of the Agent Card after the client has authenticated. This endpoint is available only if `AgentCard.supportsAuthenticatedExtendedCard` is `true`. ### Method GET ### Endpoint `{AgentCard.url}/../agent/authenticatedExtendedCard` (relative to the base URL specified in the public Agent Card). ### Authentication The client MUST authenticate the request using one of the schemes declared in the public `AgentCard.securitySchemes` and `AgentCard.security` fields. ### Parameters #### Query Parameters None are defined by the standard. Any parameters would be included as HTTP query parameters if needed. ### Request Example None provided as this is a GET request without a body. ### Response #### Success Response (200) - **AgentCard** (object) - A complete Agent Card object, which may contain additional details or skills not present in the public card. #### Response Example ```json { "version": "1.0", "name": "Example Agent", "description": "An example agent card.", "url": "http://example.com/agent", "capabilities": [ "authenticatedExtendedCard" ], "supportsAuthenticatedExtendedCard": true, "securitySchemes": { "basicAuth": { "type": "http", "scheme": "basic" } }, "security": [ { "basicAuth": [] } ] } ``` #### Error Response - **401 Unauthorized**: Authentication failed (missing or invalid credentials). The server SHOULD include a `WWW-Authenticate` header. - **403 Forbidden**: Authentication succeeded, but the client/user is not authorized to access the extended card. - **404 Not Found**: The `supportsAuthenticatedExtendedCard` capability is declared, but the server has not implemented this endpoint at the specified path. - **5xx Server Error**: An internal server error occurred. ``` -------------------------------- ### v0.3 Agent Card Query Callback Source: https://github.com/a2aproject/a2a-dotnet/blob/main/docs/taskmanager-migration-guide.md Illustrates the v0.3 method of handling agent card queries using a callback delegate. ```csharp taskManager.OnAgentCardQuery = (url, ct) => Task.FromResult(new AgentCard { Name = "My Agent", Url = url, ... }); ``` -------------------------------- ### API Reference Format Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Details the structure and content for documenting API operations, including signatures, parameters, return types, error conditions, and examples. ```APIDOC ## [HTTP_METHOD] [ENDPOINT] ### Description [Brief description of what this endpoint does] ### Method [HTTP method: GET, POST, PUT, DELETE, etc.] ### Endpoint [Full endpoint path with any path parameters] ### Parameters #### Path Parameters - **param1** (type) - Required/Optional - Description #### Query Parameters - **param1** (type) - Required/Optional - Description #### Request Body - **field1** (type) - Required/Optional - Description ### Request Example { "example": "request body" } ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example { "example": "response body" } ERROR HANDLING: - [Specific error handling details or patterns] ``` -------------------------------- ### Initialize A2AClient with Custom HttpClient Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/configuration.md Creates an A2AClient instance using a pre-configured HttpClient. This allows for custom settings like request timeouts. ```csharp var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; var client = new A2AClient(new Uri("http://localhost:5000/agent"), httpClient); ``` -------------------------------- ### Get Task Status Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/a2a-client.md Retrieve the current status and details of a specific agent task using its ID. This method throws an A2AException if the task is not found. ```csharp var task = await client.GetTaskAsync(new GetTaskRequest { Id = "task-123" }); Console.WriteLine($"Task status: {task.Status.State}"); ``` -------------------------------- ### TypeScript Type for AuthenticatedExtendedCardResponse Source: https://github.com/a2aproject/a2a-dotnet/blob/main/tests/A2A.AspNetCore.UnitTests/specification.md Defines the TypeScript type for the response body of a successful GET request to the /agent/authenticatedExtendedCard endpoint. The response conforms to the AgentCard interface. ```typescript // The response body for a successful GET request to /agent/authenticatedExtendedCard // is a complete AgentCard object. type AuthenticatedExtendedCardResponse = AgentCard; ``` -------------------------------- ### Client Request with JSON Schema Hint Source: https://github.com/a2aproject/a2a-dotnet/blob/main/tests/A2A.AspNetCore.UnitTests/specification.md Client sends a message/send request, using `Part.metadata` to hint at the desired JSON output schema and MIME type for the response. ```json { "jsonrpc": "2.0", "id": 9, "method": "message/send", "params": { "message": { "role": "user", "parts": [ { "type": "text", "text": "Show me a list of my open IT tickets", "metadata": { "mimeType": "application/json", "schema": { "type": "array", "items": { "type": "object", "properties": { "ticketNumber": { "type": "string" }, "description": { "type": "string" } } } } } } ], "messageId": "85b26db5-ffbb-4278-a5da-a7b09dea1b47" }, "metadata": {} } } ``` -------------------------------- ### UserText Property Example Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/request-context.md Demonstrates how to access and use the UserText property, which extracts the first text part from the message. This is useful for simple text-based user inputs. ```csharp if (context.UserText != null) { Console.WriteLine($"User said: {context.UserText}"); } ``` -------------------------------- ### GetExtendedAgentCardAsync Method Signature Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/a2a-server.md Retrieves the extended agent card. Use this method to get the extended agent card if it is configured. It requires a GetExtendedAgentCardRequest and an optional CancellationToken. ```csharp public Task GetExtendedAgentCardAsync( GetExtendedAgentCardRequest request, CancellationToken cancellationToken = default) ``` -------------------------------- ### GetAgentCardAsync Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/a2a-card-resolver.md Retrieves the agent card from the well-known endpoint. This method performs an HTTP GET request and returns the agent's capabilities, skills, and endpoint information. ```APIDOC ## GetAgentCardAsync ### Description Retrieves the agent card from the well-known endpoint. The resolver performs an HTTP GET request to the agent card endpoint. ### Method GET ### Endpoint `/.well-known/agent-card.json` (relative to the base URL provided during construction) ### Parameters #### Query Parameters - **cancellationToken** (`CancellationToken`) - Optional - Allows cancellation of the operation. ### Response #### Success Response (200) - **AgentCard** (`Task`) - The deserialized agent card containing capabilities, skills, and endpoint information. ### Throws - `A2AException` — If the agent card cannot be parsed as valid JSON or if the HTTP request fails. - `HttpRequestException` — If the HTTP request encounters a network error. - `JsonException` — If the response body contains invalid JSON. ### Example ```csharp var resolver = new A2ACardResolver(new Uri("http://localhost:5000/")); var agentCard = await resolver.GetAgentCardAsync(); Console.WriteLine($"Agent: {agentCard.Name}"); Console.WriteLine($"Version: {agentCard.Version}"); Console.WriteLine($"Capabilities: Streaming={agentCard.Capabilities.Streaming}"); // Create client using the discovered endpoint var client = new A2AClient(new Uri(agentCard.SupportedInterfaces[0].Url)); ``` ``` -------------------------------- ### Configuration Reference Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Details on configuration options for setting up and customizing the A2A client and related components. ```APIDOC ## configuration.md ### Description Details on configuration options for setting up and customizing the A2A client and related components. ### Configuration Options #### HttpClient.BaseAddress - **Type**: `System.Uri` - **Default Value**: `null` - **Behavior**: Specifies the base address for all HTTP requests made by the A2A client. If not set, absolute URIs must be provided for each request. - **Code Example**: ```csharp var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri("https://api.a2a.example.com/v1/"); // Now requests can be relative: var response = await httpClient.GetAsync("status"); ``` #### Agent2Agent.ProtocolVersion - **Type**: `string` - **Default Value**: `"1.0"` - **Behavior**: Sets the A2A protocol version to use for communication. Ensure compatibility with the server. - **Code Example**: ```csharp // Using environment variable Environment.SetEnvironmentVariable("Agent2Agent__ProtocolVersion", "0.3"); // Or directly in configuration var config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary { {"Agent2Agent:ProtocolVersion", "0.3"} }) .Build(); ``` ``` -------------------------------- ### A2AClient Constructor Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/a2a-client.md Initializes a new instance of the A2AClient class. Use this to specify the agent's base URL and an optional HttpClient. ```csharp public sealed class A2AClient : IA2AClient { public A2AClient(Uri baseUrl, HttpClient? httpClient = null); } ``` -------------------------------- ### GetTaskPushNotificationConfigAsync Method Signature Source: https://github.com/a2aproject/a2a-dotnet/blob/main/_autodocs/api-reference/a2a-server.md Retrieves a push notification configuration by ID. Call this method to get the details of an existing notification configuration. It requires a GetTaskPushNotificationConfigRequest and an optional CancellationToken. ```csharp public Task GetTaskPushNotificationConfigAsync( GetTaskPushNotificationConfigRequest request, CancellationToken cancellationToken = default) ```