diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 178fcbb8..ad678d16 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -54,4 +54,18 @@ All publishing steps are currently commented out as requested. To enable publish The workflow uses dependency caching to speed up builds: - Python: pip cache - JavaScript: npm cache -- .NET: NuGet packages are cached automatically by the dotnet CLI \ No newline at end of file +- .NET: NuGet packages are cached automatically by the dotnet CLI + +## 📋 Telemetry + +Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. + +## Trademarks + +*Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* + +## License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the MIT License - see the [LICENSE](../../LICENSE.md) file for details. diff --git a/README.md b/README.md index 94a926d0..25c5f04c 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,125 @@ -# Microsoft Agent365 SDK for TypeScript +# Microsoft Agent 365 SDK - Node.js/TypeScript -The Microsoft Agent365 SDK provides comprehensive observability, tooling, and runtime capabilities for AI agents and tools built with TypeScript/Node.js. +[![npm](https://img.shields.io/npm/v/@microsoft/agents-a365-observability?label=npm&logo=npm)](https://www.npmjs.com/search?q=%40microsoft%2Fagents-a365) +[![npm Downloads](https://img.shields.io/npm/dm/@microsoft/agents-a365-observability?label=Downloads&logo=npm)](https://www.npmjs.com/search?q=%40microsoft%2Fagents-a365) +[![Build Status](https://img.shields.io/github/actions/workflow/status/microsoft/Agent365-nodejs/build.yml?branch=main&label=Build&logo=github)](https://github.com/microsoft/Agent365-nodejs/actions) +[![License](https://img.shields.io/github/license/microsoft/Agent365-nodejs?label=License)](LICENSE.md) +[![Node.js Version](https://img.shields.io/badge/Node.js-18%2B-339933?logo=node.js)](https://nodejs.org/) +[![Contributors](https://img.shields.io/github/contributors/microsoft/Agent365-nodejs?label=Contributors&logo=github)](https://github.com/microsoft/Agent365-nodejs/graphs/contributors) -## 📦 Packages +> #### Note: +> Use the information in this README to contribute to this open-source project. To learn about using this SDK in your projects, refer to the [Microsoft Agent 365 developer documentation](https://learn.microsoft.com/microsoft-agent-365/developer/). -This monorepo contains several specialized packages: +The Microsoft Agent 365 SDK extends the Microsoft 365 Agents SDK with enterprise-grade capabilities for building sophisticated agents. This SDK provides comprehensive tooling for observability, notifications, runtime utilities, and development tools that help developers create production-ready agents for platforms including M365, Teams, Copilot Studio, and Webchat. -### 🔍 **Observability** -- **[@microsoft/agents-a365-observability](./packages/agents-a365-observability/README.md)** - OpenTelemetry-based tracing and monitoring for AI agents - - Agent invocation tracking with caller context - - Tool execution monitoring with endpoint support - - LLM inference telemetry with granular token tracking - - Baggage propagation for distributed agent systems +The Microsoft Agent 365 SDK focuses on four core areas: -### 🛠️ **Tooling & Extensions** -- **[@microsoft/agents-a365-tooling](./packages/agents-a365-tooling/README.md)** - Core MCP (Model Context Protocol) tooling infrastructure -- **[@microsoft/agents-a365-tooling-extensions-claude](./packages/agents-a365-tooling-extensions-claude/README.md)** - Claude/Anthropic integration -- **[@microsoft/agents-a365-tooling-extensions-langchain](./packages/agents-a365-tooling-extensions-langchain/README.md)** - LangChain integration -- **[@microsoft/agents-a365-tooling-extensions-openai](./packages/agents-a365-tooling-extensions-openai/README.md)** - OpenAI integration +- **Observability**: Comprehensive tracing, caching, and monitoring capabilities for agent applications +- **Notifications**: Agent notification services and models for handling user notifications +- **Runtime**: Core utilities and extensions for agent runtime operations +- **Tooling**: Developer tools and utilities for building sophisticated agent applications -### 🚀 **Runtime & Infrastructure** -- **[@microsoft/agents-a365-runtime](./packages/agents-a365-runtime/README.md)** - Authentication, authorization, and Power Platform integration -- **[@microsoft/agents-a365-notifications](./packages/agents-a365-notifications/README.md)** - Agent notification and messaging system +## Current Project State +This project is currently in active development. Packages are published to npm as they become available. -## 📋 **Package Overview** +### Public npm feed -| Package | Purpose | Key Features | -|---------|---------|--------------| -| **Observability** | Monitoring & Tracing | OpenTelemetry, Azure Monitor, Agent/Tool/Inference tracking | -| **Tooling** | MCP Infrastructure | Tool registration, configuration, server management | -| **Runtime** | Auth & Platform | Microsoft identity, Power Platform APIs, token management | -| **Notifications** | Messaging | Agent notifications, email integration, activity tracking | -| **Extensions** | LLM Integrations | OpenAI, Claude, LangChain tool registration | +The best way to consume this SDK is via our npm packages found here: [npmjs.com](https://www.npmjs.com/search?q=%40microsoft%2Fagents-a365). All packages begin with **@microsoft/agents-a365**. +## Working with this codebase -## 📋 **Telemetry** +### Prerequisites + +- Node.js 18 or later +- pnpm package manager +- Git + +### Building the project + +1. Clone the repository: + + ```bash + git clone https://github.com/microsoft/Agent365-nodejs.git + cd Agent365-nodejs + ``` + +2. Install dependencies: + + ```bash + pnpm install + ``` + +3. Build the packages: + + ```bash + # Build all packages + pnpm build + ``` + +4. Run tests: + + ```bash + pnpm test + ``` + +For more detailed build instructions, see the [HOW_TO_BUILD.md](HOW_TO_BUILD.md). + +## Project Structure + +- **packages/agents-a365-notifications**: Microsoft Agent 365 Notifications SDK - Agent notification services and models +- **packages/agents-a365-observability**: Microsoft Agent 365 Observability Core - Core observability functionality +- **packages/agents-a365-observability-extensions-openai**: OpenAI observability extensions +- **packages/agents-a365-runtime**: Microsoft Agent 365 Runtime - Core runtime utilities and extensions +- **packages/agents-a365-tooling**: Microsoft Agent 365 Tooling SDK - Agent tooling and MCP integration +- **packages/agents-a365-tooling-extensions-claude**: Claude/Anthropic tooling extensions +- **packages/agents-a365-tooling-extensions-langchain**: LangChain tooling extensions +- **packages/agents-a365-tooling-extensions-openai**: OpenAI tooling extensions +- For sample applications, see the [Microsoft Agent 365 SDK Samples repository](https://github.com/microsoft/Agent365-Samples) +- **tests/**: Unit and integration tests + +## Support + +For issues, questions, or feedback: + +- **Issues**: Please file issues in the [GitHub Issues](https://github.com/microsoft/Agent365-nodejs/issues) section +- **Documentation**: See the [Microsoft Agent 365 developer documentation](https://learn.microsoft.com/microsoft-agent-365/developer/) +- **Security**: For security issues, please see [SECURITY.md](SECURITY.md) + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit . + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## Useful Links + +### Microsoft 365 Agents SDK + +The core SDK for building conversational AI agents for Microsoft 365 platforms. + +- [Microsoft 365 Agents SDK - C# /.NET repository](https://github.com/Microsoft/Agents-for-net) +- [Microsoft 365 Agents SDK - NodeJS /TypeScript repository](https://github.com/Microsoft/Agents-for-js) +- [Microsoft 365 Agents SDK - Python repository](https://github.com/Microsoft/Agents-for-python) +- [Microsoft 365 Agents documentation](https://learn.microsoft.com/microsoft-365/agents-sdk/) + +### Microsoft Agent 365 SDK + +Enterprise-grade extensions for observability, notifications, runtime utilities, and developer tools. + +- [Microsoft Agent 365 SDK - C# /.NET repository](https://github.com/microsoft/Agent365-dotnet) +- [Microsoft Agent 365 SDK - Python repository](https://github.com/microsoft/Agent365-python) +- [Microsoft Agent 365 SDK - Node.js/TypeScript repository](https://github.com/microsoft/Agent365-nodejs) - You are here +- [Microsoft Agent 365 SDK Samples repository](https://github.com/microsoft/Agent365-Samples) +- [Microsoft Agent 365 developer documentation](https://learn.microsoft.com/microsoft-agent-365/developer/) + +### Additional Resources + +- [Node.js documentation](https://learn.microsoft.com/javascript/api/?view=m365-agents-sdk&preserve-view=true) + +## 📋 Telemetry Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. @@ -43,9 +127,8 @@ Data Collection. The software may collect information about you and your use of *Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* +## License +Copyright (c) Microsoft Corporation. All rights reserved. - -## 📄 **License** - -This project is licensed under the MIT License - see the LICENSE file for details. +Licensed under the MIT License - see the [LICENSE](LICENSE.md) file for details. diff --git a/packages/agents-a365-notifications/README.md b/packages/agents-a365-notifications/README.md index 3a7052fd..00609f92 100644 --- a/packages/agents-a365-notifications/README.md +++ b/packages/agents-a365-notifications/README.md @@ -1,340 +1,37 @@ -# Agent Notifications SDK for Node.js +# @microsoft/agents-a365-notifications -This package provides TypeScript/Node.js support for handling agent notifications in Microsoft 365 Agent applications, including email and document collaboration notifications. +[![npm](https://img.shields.io/npm/v/@microsoft/agents-a365-notifications?label=npm&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-notifications) +[![npm Downloads](https://img.shields.io/npm/dm/@microsoft/agents-a365-notifications?label=Downloads&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-notifications) -## Features - -- **Type-safe notification handling** with strongly-typed models -- **Multiple notification types** including Email and Word (WPX) comments -- **Sub-channel routing** for email, Word, Excel, and PowerPoint -- **Activity extensions** for easy entity extraction -- **TypeScript-first** with comprehensive type definitions +Agent notification services and models for handling user notifications in applications built with the Microsoft Agent 365 SDK. This package provides type-safe notification handling for email, Word comments, and other collaboration scenarios. ## Installation -This package is part of the `@microsoft/agent365-sdk` workspace and is typically installed as a dependency: - ```bash npm install @microsoft/agents-a365-notifications ``` -## Models - -### Entity Types - -The SDK provides several entity types that represent different notification formats: - -#### `EmailReference` -Represents an email notification entity. - -```typescript -interface EmailReference { - type: 'emailNotification'; - id?: string; - conversationId?: string; - htmlBody?: string; -} -``` - -#### `EmailResponse` -Represents an email response to be sent back. - -```typescript -interface EmailResponse { - type: 'emailResponse'; - htmlBody?: string; -} -``` - -#### `WpxComment` -Represents a Word (WPX) comment notification. - -```typescript -interface WpxComment { - type: 'WpxComment'; - odataId?: string; - documentId?: string; - initiatingCommentId?: string; - subjectCommentId?: string; -} -``` - -### `AgentNotificationActivity` - -A parsed notification activity with strongly-typed notification data: - -```typescript -interface AgentNotificationActivity { - wpxCommentNotification?: WpxComment; - emailNotification?: EmailReference; - notificationType: NotificationType; - conversation?: ConversationAccount; - from: ChannelAccount; - recipient: ChannelAccount; - channelData: any; - text: string; -} -``` - -### `NotificationType` Enum - -```typescript -enum NotificationType { - Unknown = 0, - WpxComment = 1, - EmailNotification = 2, -} -``` - ## Usage -### Basic Notification Handling - -Handle all agent notifications across all sub-channels: - -```typescript -import { AgentApplication, TurnState } from '@microsoft/agents-hosting'; -import { - AgentNotificationActivity, - NotificationType -} from '@microsoft/agents-a365-notifications'; - -const app = new AgentApplication(); - -app.onAgentNotification('*', async (context, state, notification) => { - switch (notification.notificationType) { - case NotificationType.EmailNotification: - console.log('Email notification:', notification.emailNotification); - break; - case NotificationType.WpxComment: - console.log('Word comment:', notification.wpxCommentNotification); - break; - } -}); -``` - -### Email-Specific Notifications - -Handle only email notifications: - -```typescript -import { createEmailResponse } from '@microsoft/agents-a365-notifications'; - -app.onAgenticEmailNotification(async (context, state, notification) => { - const email = notification.emailNotification; - - if (!email) { - await context.sendActivity('No email found'); - return; - } - - // Process the email - console.log('Email ID:', email.id); - console.log('Conversation ID:', email.conversationId); - - // Send a response - const response = createEmailResponse('

Thank you for your email!

'); - await context.sendActivity({ - type: 'message', - entities: [response], - }); -}); -``` - -### Word Document Notifications - -Handle Word document comment notifications: - -```typescript -import '@microsoft/agents-a365-notifications'; - -app.onAgenticWordNotification(async (context, state, notification) => { - const comment = notification.wpxCommentNotification; - - if (!comment) { - await context.sendActivity('No comment found'); - return; - } - - console.log('Document ID:', comment.documentId); - console.log('Comment ID:', comment.initiatingCommentId); +For detailed usage examples and implementation guidance, see the [Microsoft Agent 365 Notification Documentation](https://learn.microsoft.com/microsoft-agent-365/developer/notification?tabs=nodejs). - // Respond to the comment - await context.sendActivity({ - type: 'message', - text: 'Thank you for your comment!', - }); -}); -``` - -### Excel and PowerPoint Notifications - -```typescript -import '@microsoft/agents-a365-notifications'; - -app.onAgenticExcelNotification(async (context, state, notification) => { - // Handle Excel notifications - console.log('Excel notification received'); -}); - -app.onAgenticPowerPointNotification(async (context, state, notification) => { - // Handle PowerPoint notifications - console.log('PowerPoint notification received'); -}); -``` - -### Advanced: Custom Options - -All notification handlers support custom options: - -```typescript -import '@microsoft/agents-a365-notifications'; - -app.onAgentNotification( - '*' - async (context, state, notification) => { - // Handler logic - }, - { - subChannelId: 'email', // or '*' for all - rank: 100, // Route priority (lower = higher priority) - autoSignInHandlers: ['agentic'], // Auto sign-in configuration - } -); -``` - -## Type Guards and Factory Functions - -### Type Guards - -```typescript -import { isEmailReference, isWpxComment } from '@microsoft/agents-a365-notifications'; - -if (isEmailReference(entity)) { - // TypeScript knows this is EmailReference - console.log(entity.id); -} - -if (isWpxComment(entity)) { - // TypeScript knows this is WpxComment - console.log(entity.documentId); -} -``` - -### Factory Functions - -```typescript -import { - createEmailReference, - createEmailResponse, - createWpxComment -} from '@microsoft/agents-a365-notifications'; - -// Create entities -const email = createEmailReference('email-id', 'conv-id', '

Body

'); -const response = createEmailResponse('

Response body

'); -const comment = createWpxComment('odata-id', 'doc-id', 'comment-id'); -``` - -## Complete Example - -```typescript -import { AgentApplication, TurnState } from '@microsoft/agents-hosting'; -import { - NotificationType, - createEmailResponse, -} from '@microsoft/agents-a365-notifications'; - -const app = new AgentApplication(); - -app.onAgentNotification( - '*', - async (context, state, notification) => { - const { notificationType, emailNotification, wpxCommentNotification } = notification; - - switch (notificationType) { - case NotificationType.EmailNotification: - if (!emailNotification) break; - - // Process email - const emailResponse = await processEmail(emailNotification); - - // Send response - const response = createEmailResponse(emailResponse); - await context.sendActivity({ - type: 'message', - entities: [response], - }); - break; - - case NotificationType.WpxComment: - if (!wpxCommentNotification) break; - - // Process Word comment - const commentResponse = await processComment(wpxCommentNotification); +## Support - // Send response - await context.sendActivity({ - type: 'message', - text: commentResponse, - }); - break; +For issues, questions, or feedback: - default: - await context.sendActivity('Unknown notification type'); - } - }, - { - rank: 100, - autoSignInHandlers: ['agentic'], - } -); +- File issues in the [GitHub Issues](https://github.com/microsoft/Agent365-nodejs/issues) section +- See the [main documentation](../../README.md) for more information -async function processEmail(email: EmailReference): Promise { - // Your email processing logic - return `

Processed email ${email.id}

`; -} +## 📋 Telemetry -async function processComment(comment: WpxComment): Promise { - // Your comment processing logic - return `Processed comment on document ${comment.documentId}`; -} -``` - -## Migration from Legacy API - -If you're using the legacy `AddRoute` and `OnAgentNotification` functions, they are still available but deprecated: - -```typescript -// Legacy (deprecated) -import { AddRoute, OnAgentNotification } from '@microsoft/agents-a365-notifications'; - -OnAgentNotification(app, '*', async (context, state) => { - // Handler logic -}); +Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. -// New approach (recommended) -import '@microsoft/agents-a365-notifications'; +## Trademarks -app.onAgentNotification('*', async (context, state, notification) => { - // Handler with typed notification -}); -``` - -## Constants - -```typescript -export const AGENTS_CHANNEL = 'agents'; -export const AGENTS_EMAIL_SUBCHANNEL = 'email'; -export const AGENTS_EXCEL_SUBCHANNEL = 'excel'; -export const AGENTS_WORD_SUBCHANNEL = 'word'; -export const AGENTS_POWERPOINT_SUBCHANNEL = 'powerpoint'; -``` +*Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* ## License -See the main repository license file. - -## Contributing +Copyright (c) Microsoft Corporation. All rights reserved. -Contributions are welcome! Please see the main repository for contribution guidelines. +Licensed under the MIT License - see the [LICENSE](../../LICENSE.md) file for details diff --git a/packages/agents-a365-observability-extensions-openai/README.md b/packages/agents-a365-observability-extensions-openai/README.md index 1061fc1d..30b5c14c 100644 --- a/packages/agents-a365-observability-extensions-openai/README.md +++ b/packages/agents-a365-observability-extensions-openai/README.md @@ -1,16 +1,9 @@ # @microsoft/agents-a365-observability-extensions-openai -OpenAI Agents SDK instrumentation extensions for Agent365 telemetry and observability. +[![npm](https://img.shields.io/npm/v/@microsoft/agents-a365-observability-extensions-openai?label=npm&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-observability-extensions-openai) +[![npm Downloads](https://img.shields.io/npm/dm/@microsoft/agents-a365-observability-extensions-openai?label=Downloads&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-observability-extensions-openai) -## Overview - -This package provides OpenTelemetry instrumentation for Agent365 which uses OpenAI Agents SDK, enabling automatic tracing and telemetry collection for agent operations, function calls, and AI model interactions. - -## Features - -- **Automatic Instrumentation**: Seamlessly instruments OpenAI Agents SDK without manual instrumentation. -- **OpenTelemetry Integration**: Full compatibility with OpenTelemetry ecosystem -- **Comprehensive Tracing**: Captures agent operations, function calls, AI generations +OpenAI Agents SDK instrumentation for the Microsoft Agent 365 Observability SDK. This package provides automatic OpenTelemetry tracing and telemetry collection for OpenAI Agents SDK operations, including agent execution, function calls, and AI model interactions. ## Installation @@ -18,305 +11,27 @@ This package provides OpenTelemetry instrumentation for Agent365 which uses Open npm install @microsoft/agents-a365-observability-extensions-openai ``` -## Prerequisites - -- Node.js 18.0.0 or higher -- @openai/agents 0.1.5 or higher -- @microsoft/agents-a365-observability configured and initialized - ## Usage -### Basic Setup - -```typescript -import { ObservabilityManager } from '@microsoft/agents-a365-observability'; -```typescript -import { OpenAIAgentsTraceInstrumentor } from '@microsoft/agents-a365-observability-extensions-openai'; - -// Configure observability first -const sdk = ObservabilityManager.configure((builder) => - builder - .withService('My Agent Service', '1.0.0') - .withConsoleExporter(true) -); - -// Create and enable the instrumentor -const instrumentor = new OpenAIAgentsTraceInstrumentor({ - enabled: true, - tracerName: 'openai-agents-tracer', - tracerVersion: '1.0.0' -}); - -sdk.start(); - -instrumentor.enable(); -``` - -### Configuration Options - -```typescript -interface OpenAIAgentsInstrumentationConfig { - // Enable/disable instrumentation - enabled?: boolean; - - // Custom tracer configuration - tracerName?: string; - tracerVersion?: string; -} -``` - -### Automatic Tracing - -Once configured, the instrumentor automatically traces: - -- **Agent Operations**: Agent initialization, execution, and lifecycle -- **Function Calls**: Tool invocations with input/output parameters -- **AI Generations**: Model calls with prompts, responses, and token usage -- **Errors**: Exception handling and error propagation - -### Span Attributes - -The instrumentor captures rich telemetry attributes following OpenTelemetry semantic conventions: - -#### Generation Spans -- `gen_ai.provider.name`: AI provider (always "openai") -- `gen_ai.request.model`: Model name (e.g., "gpt-4") -- `gen_ai.request.content`: Input prompt/messages -- `gen_ai.response.content`: Model response -- `gen_ai.response.id`: Response identifier -- `gen_ai.usage.input_tokens`: Input token count -- `gen_ai.usage.output_tokens`: Output token count - -#### Function Spans -- `gen_ai.tool.name`: Function/tool name -- `gen_ai.request.content`: Function input parameters -- `gen_ai.response.content`: Function output/result +For detailed usage examples and implementation guidance, see the [Microsoft Agent 365 Observability Documentation](https://learn.microsoft.com/microsoft-agent-365/developer/observability?tabs=nodejs). -#### Agent Spans -- Agent metadata and execution context -- Session and conversation identifiers -- Performance metrics +## Support -## Advanced Usage +For issues, questions, or feedback: -### Custom Processor Access +- File issues in the [GitHub Issues](https://github.com/microsoft/Agent365-nodejs/issues) section +- See the [main documentation](../../README.md) for more information -```typescript -const instrumentor = new OpenAIAgentsTraceInstrumentor(); -instrumentor.enable(); +## 📋 Telemetry +Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. -``` - -### Lifecycle Management - -```typescript -// Enable instrumentation -instrumentor.enable(); - -// Your application code using OpenAI Agents SDK -// Traces will be automatically collected - -// Disable when shutting down -instrumentor.disable(); - -// Shutdown observability -await ObservabilityManager.shutdown(); -``` - -## Trace Data Structure - -The instrumentor processes various span types from the OpenAI Agents SDK: - -- **Agent Spans**: High-level agent operations and workflows -- **Function Spans**: Tool and function executions -- **Response Spans**: Model response processing - -## Error Handling +## Trademarks -The instrumentor gracefully handles errors and provides detailed error tracking: - -- Automatic error detection in spans -- Error message and stack trace capture -- Span status reporting (OK/ERROR) -- Silent failure for non-critical operations - -## Compatibility - -- **OpenAI Agents SDK**: 0.1.5 or higher -- **OpenTelemetry**: 1.9.0 or higher -- **Node.js**: 18.0.0 or higher -- **TypeScript**: 5.5.0 or higher - -## Complete Example -See the complete working example in [tests-agent/openai-agent-auto-instrument-sample/](../../tests-agent/openai-agent-auto-instrument-sample/README.md) - -## Trace examples -``` -{ - resource: { - attributes: { - 'service.name': 'TypeScript Sample Agent', - 'host.name': 'pefan4-0', - 'host.arch': 'amd64', - 'host.id': '3dc679db-f652-4002-98b7-5e05e5071507', - 'process.pid': 3612, - 'process.executable.name': 'npm start', - 'process.executable.path': 'C:\\Program Files\\nodejs\\node.exe', - 'process.command_args': [ - 'C:\\Program Files\\nodejs\\node.exe', - 'D:\\repos\\sdk\\Agent365\\nodejs\\samples\\openai-agents-sdk\\dist\\index.js' - ], - 'process.runtime.version': '20.18.3', - 'process.runtime.name': 'nodejs', - 'process.runtime.description': 'Node.js', - 'process.command': 'D:\\repos\\sdk\\Agent365\\nodejs\\samples\\openai-agents-sdk\\dist\\index.js', - 'process.owner': 'pefan', - 'telemetry.sdk.language': 'nodejs', - 'telemetry.sdk.name': 'opentelemetry', - 'telemetry.sdk.version': '2.1.0' - } - }, - instrumentationScope: { - name: 'openai-agents-tracer', - version: '1.0.0', - schemaUrl: undefined - }, - traceId: '89fb62eb0d8a5658436fdd8eefb76942', - parentSpanContext: { - traceId: '89fb62eb0d8a5658436fdd8eefb76942', - spanId: '545cbb53a808dc19', - traceFlags: 1, - traceState: undefined - }, - traceState: undefined, - name: 'execute_tool OneDriveMCPServer', - id: '8f1a1cbe99cf4ef6', - kind: 0, - timestamp: 1761155395568000, - duration: 5000, - attributes: { - 'gen_ai.operation.name': 'execute_tool', - 'gen_ai.system': 'openai', - 'gen_ai.agent.id': 'REPLACE-WITH-YOUR-AGENT-ID-BUT-THIS-WILL-GO-AWAY-SOON', - 'gen_ai.event.content': '["graph_onedrive_createFolder","graph_onedrive_deleteFileOrFolder","graph_onedrive_listAllFiles","graph_onedrive_moveFileOrFolder","graph_onedrive_shareFileOrFolder"]', - 'gen_ai.tool.name': 'OneDriveMCPServer', - 'gen_ai.tool.type': 'extension' - }, - status: { code: 1 }, - events: [], - links: [] -} -{ - resource: { - attributes: { - 'service.name': 'TypeScript Sample Agent', - 'host.name': 'pefan4-0', - 'host.arch': 'amd64', - 'host.id': '3dc679db-f652-4002-98b7-5e05e5071507', - 'process.pid': 4448, - 'process.executable.name': 'C:\\Program Files\\PowerShell\\7\\pwsh.exe', - 'process.executable.path': 'C:\\Program Files\\nodejs\\node.exe', - 'process.command_args': [ - 'C:\\Program Files\\nodejs\\node.exe', - 'D:\\repos\\sdk\\Agent365\\nodejs\\samples\\openai-agents-sdk\\dist\\index.js' - ], - 'process.runtime.version': '20.18.3', - 'process.runtime.name': 'nodejs', - 'process.runtime.description': 'Node.js', - 'process.command': 'D:\\repos\\sdk\\Agent365\\nodejs\\samples\\openai-agents-sdk\\dist\\index.js', - 'process.owner': 'pefan', - 'telemetry.sdk.language': 'nodejs', - 'telemetry.sdk.name': 'opentelemetry', - 'telemetry.sdk.version': '2.1.0' - } - }, - instrumentationScope: { - name: 'openai-agents-tracer', - version: '1.0.0', - schemaUrl: undefined - }, - traceId: '8f9ebc7dc174208cd21a4d3939ef4455', - parentSpanContext: undefined, - traceState: undefined, - name: 'invoke_agent OpenAI Agent', - id: 'b98b2404088f8db4', - kind: 0, - timestamp: 1761063701211000, - duration: 348000, - attributes: { - 'gen_ai.operation.name': 'invoke_agent', - 'gen_ai.system': 'openai', - 'gen_ai.agent.id': 'REPLACE-WITH-YOUR-AGENT-ID-BUT-THIS-WILL-GO-AWAY-SOON', - graph_node_id: 'OpenAI Agent' - }, - status: { code: 2, message: 'Error in agent run' }, - events: [], - links: [] -} -{ - resource: { - attributes: { - 'service.name': 'TypeScript Sample Agent', - 'host.name': 'pefan4-0', - 'host.arch': 'amd64', - 'host.id': '3dc679db-f652-4002-98b7-5e05e5071507', - 'process.pid': 53888, - 'process.executable.name': 'npm start', - 'process.executable.path': 'C:\\Program Files\\nodejs\\node.exe', - 'process.command_args': [ - 'C:\\Program Files\\nodejs\\node.exe', - 'D:\\repos\\sdk\\Agent365\\nodejs\\samples\\openai-agents-sdk\\dist\\index.js' - ], - 'process.runtime.version': '20.18.3', - 'process.runtime.name': 'nodejs', - 'process.runtime.description': 'Node.js', - 'process.command': 'D:\\repos\\sdk\\Agent365\\nodejs\\samples\\openai-agents-sdk\\dist\\index.js', - 'process.owner': 'pefan', - 'telemetry.sdk.language': 'nodejs', - 'telemetry.sdk.name': 'opentelemetry', - 'telemetry.sdk.version': '2.1.0' - } - }, - instrumentationScope: { - name: 'openai-agents-tracer', - version: '1.0.0', - schemaUrl: undefined - }, - traceId: '0f3cffc86d53373b64ac760d4d2ad489', - parentSpanContext: { - traceId: '0f3cffc86d53373b64ac760d4d2ad489', - spanId: '148c242fffd8d4d0', - traceFlags: 1, - traceState: undefined - }, - traceState: undefined, - name: 'chat gpt-4o-mini-2024-07-18', - id: '891ba741248959c1', - kind: 0, - timestamp: 1761152107806000, - duration: 6392000, - attributes: { - 'gen_ai.operation.name': 'chat', - 'gen_ai.system': 'openai', - 'gen_ai.agent.id': 'REPLACE-WITH-YOUR-AGENT-ID-BUT-THIS-WILL-GO-AWAY-SOON', - 'gen_ai.output.messages': `[{"id":"msg_06db8f945b1be6ff0068f90c6db78081a094b3e2975f51ee9c","type":"message","status":"completed","content":[{"type":"output_text","annotations":[],"logprobs":[],"text":"Determining the \\"best\\" park in the U.S. can be subjective, as it depends on personal preferences. However, some of the most highly regarded national parks include:\\n\\n1. **Yosemite National Park (California)** - Famous for its stunning granite cliffs, waterfalls, and diverse ecosystems.\\n2. **Yellowstone National Park (Wyoming, Montana, Idaho)** - Known for its geothermal features, wildlife, and expansive landscapes.\\n3. **Grand Canyon National Park (Arizona)** - Renowned for its awe-inspiring canyon views and hiking opportunities.\\n4. **Zion National Park (Utah)** - Celebrated for its dramatic cliffs, canyons, and hiking trails.\\n5. **Great Smoky Mountains National Park (Tennessee, North Carolina)** - Valued for its biodiversity and beautiful scenery.\\n\\nEach park offers unique experiences, so the \\"best\\" one depends on what you're looking for!"}],"role":"assistant"}]`, - 'gen_ai.request.model': 'gpt-4o-mini-2024-07-18', - 'gen_ai.usage.input_tokens': 14, - 'gen_ai.usage.output_tokens': 185, - llm_token_count_total: 199, - 'gen_ai.input.messages': '[{"type":"message","role":"user","content":"which is the best park in US"}]' - }, - status: { code: 1 }, - events: [], - links: [] -} -``` - -## Contributing - -This project welcomes contributions and suggestions. Please follow the contributing guidelines in the main repository. +*Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* ## License -This project is licensed under the MIT License - see the [LICENSE](../../../LICENSE.md) file for details. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the MIT License - see the [LICENSE](../../LICENSE.md) file for details diff --git a/packages/agents-a365-observability/README.md b/packages/agents-a365-observability/README.md index 42b2d36b..4781baed 100644 --- a/packages/agents-a365-observability/README.md +++ b/packages/agents-a365-observability/README.md @@ -1,508 +1,37 @@ -# Agent365 Observability SDK for Node.js +# @microsoft/agents-a365-observability -## 🚀 Features +[![npm](https://img.shields.io/npm/v/@microsoft/agents-a365-observability?label=npm&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-observability) +[![npm Downloads](https://img.shields.io/npm/dm/@microsoft/agents-a365-observability?label=Downloads&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-observability) -- **🔍 Agent Monitoring**: Specialized tracing for AI agent invocations with detailed telemetry -- **🛠️ Tool Execution Tracking**: Monitor tool executions and function calls with comprehensive metrics -- **📊 OpenTelemetry Integration**: Built-in OpenTelemetry tracing for standardized observability -- **☁️ Azure Monitor Support**: Seamless integration with Azure Monitor for cloud-based monitoring -- **🧳 Baggage Propagation**: Context propagation across distributed agent systems -- **🎯 Multiple Span Types**: Support for invoke agent, execute tool, and inference call spans -- **👤 Enhanced Caller Tracking**: Detailed agent information with caller details and agent metadata -- **🌐 Service Endpoint Support**: Track service endpoints with host, port, and protocol information -- **🧠 Granular Inference Telemetry**: Token counting, message recording, and finish reason tracking -- **↔️ C# Implementation Parity**: Full feature compatibility with the C# observability SDK +OpenTelemetry-based observability and tracing for Microsoft Agents A365 applications. This package provides comprehensive monitoring capabilities for agent invocations, tool executions, and AI model inference calls with seamless Azure Monitor integration. -## 📋 Table of Contents - -- [Installation](#installation) -- [Environment Variables](#environment-variables) -- [Quick Start](#quick-start) -- [Configuration](#configuration) -- [Span Types](#span-types) -- [Baggage Usage](#baggage-usage) -- [Enhanced Interfaces](#enhanced-interfaces) -- [Advanced Usage](#advanced-usage) - -## 📦 Installation - -Install the package via npm: +## Installation ```bash npm install @microsoft/agents-a365-observability ``` -## 🌍 Environment Variables - -The SDK supports various environment variables for configuration: - -### Telemetry Control -- `ENABLE_OBSERVABILITY`: Enable/disable observability (default: `false`) - - Values: `true`, `1`, `yes`, `on` (case-insensitive) -- `ENABLE_A365_OBSERVABILITY`: Alternative flag for enabling observability - - Values: `true`, `1` (case-insensitive) - -### Exporter Configuration -- `ENABLE_A365_OBSERVABILITY_EXPORTER`: Alternative flag for custom exporter - - Values: `true`, `1`, `yes`, `on` (case-insensitive) - -### Environment/Cluster Configuration -- `CLUSTER_CATEGORY`: Deployment environment (default: `prod`) - - Values: `preprod`, `prod` - -## 🚀 Quick Start - -### Basic Setup - -```typescript -import { ObservabilityManager } from '@microsoft/agents-a365-observability'; - -// Simple configuration -const sdk = ObservabilityManager.start({ - serviceName: 'my-agent-service', - serviceVersion: '1.0.0' -}); -``` - -### Using Builder Pattern - -```typescript -import { ObservabilityManager } from '@microsoft/agents-a365-observability'; -import { getUserManagedIdentityToken } from '@microsoft/agents-a365-runtime'; - -// Advanced configuration with builder pattern -const builder = ObservabilityManager.configure(builder => - builder - .withService('my-agent-service', '1.0.0') - .withTokenResolver((agentId, tenantId) => { - return getUserManagedIdentityToken(); - }) - .withClusterCategory('preprod') -); - -builder.start(); -``` - -## ⚙️ Configuration - -### BuilderOptions Interface - -```typescript -interface BuilderOptions { - /** Custom service name for telemetry */ - serviceName?: string; - - /** Custom service version for telemetry */ - serviceVersion?: string; - - /** Token resolver function for authentication */ - tokenResolver?: TokenResolver; - - /** Environment/cluster category (e.g., "preprod", "prod") */ - clusterCategory?: ClusterCategory; -} -``` - -### Token Resolver - -When using the Agent365 exporter, you must provide a token resolver function for authentication. The token resolver can be either synchronous or asynchronous: - -#### Async Token Resolver - -```typescript -import { getUserManagedIdentityToken } from '@microsoft/agents-a365-runtime'; - -// Custom async token acquisition -const customAsyncTokenResolver = async (agentId: string, tenantId: string): Promise => { - // Implement your custom token acquisition logic - const token = await getCustomTokenAsync(agentId, tenantId); - return token; -}; -``` - -#### Synchronous Token Resolver - -```typescript -// Using cached tokens -const cachedTokenResolver = (agentId: string, tenantId: string): string => { - const cacheKey = `${agentId}:${tenantId}`; - return tokenCache.get(cacheKey) || 'default-token'; -}; -``` - -### Agent Hosting Framework Integration - -When using the Agent365 Observability SDK with the Agent Hosting framework (`@microsoft/agents-hosting`), you can generate tokens using the `TurnContext` from agent activities: - -#### Token Generation with Agent Hosting - -```typescript -import { TurnContext } from '@microsoft/agents-hosting'; -import { getObservabilityAuthenticationScope } from '@microsoft/agents-a365-runtime'; - -// Generate agentic token for observability -const aauToken = await agentApplication.authorization.exchangeToken( - context, - 'agentic', - { - scopes: getObservabilityAuthenticationScope() - } -); - -// Cache the token for use by the observability token resolver -const cacheKey = createAgenticTokenCacheKey(agentInfo.agentId, tenantInfo.tenantId); -tokenCache.set(cacheKey, aauToken?.token || ''); -``` - -## 🎯 Span Types - -The SDK provides three main span types for comprehensive agent observability: - -### 1. Invoke Agent Spans - -Track agent-to-agent invocations and human-to-agent interactions with enhanced caller information: - -```typescript -import { - InvokeAgentScope, - ExecutionType, - CallerDetails, - EnhancedAgentDetails -} from '@microsoft/agents-a365-observability'; - -// Basic agent invocation details -const invokeDetails = { - agentId: 'email-agent-123', - agentName: 'Email Assistant', - agentDescription: 'AI assistant for email management', - conversationId: 'conv-456', - sessionId: 'session-789', - endpoint: { - host: 'agents.contoso.com', - port: 443, - protocol: 'https' - }, - request: { - content: 'Please help me organize my emails', - executionType: ExecutionType.HumanToAgent, - sessionId: 'session-123', - sourceMetadata: { - id: 'teams-channel-123', - name: 'General Channel', - description: 'Main team communication channel' - } - } -}; - -const tenantDetails = { - tenantId: 'tenant-789' -}; - -// Optional: Caller details (human user) -const callerDetails: CallerDetails = { - callerId: 'user-456', - callerName: 'John Doe', - callerUpn: 'john.doe@contoso.com', - callerUserId: 'userid-789', - tenantId: 'tenant-123' -}; - -// Optional: Caller agent details (for agent-to-agent calls) -const callerAgentDetails: EnhancedAgentDetails = { - agentId: 'calendar-agent-789', - agentName: 'Calendar Assistant', - agentAUID: 'agent-auid-456', - agentUPN: 'calendar-agent@contoso.com', - agentBlueprintId: 'blueprint-calendar-v1', - tenantId: 'tenant-123' -}; - -// Enhanced invocation with caller context -using scope = InvokeAgentScope.start( - invokeDetails, - tenantDetails, - callerAgentDetails, - callerDetails -); - -try { - // Record input messages - scope.recordInputMessages(['Please help me organize my emails', 'Focus on urgent items']); - - // Your agent invocation logic here - const response = await invokeAgent(invokeDetails.request.content); - - // Record output messages - scope.recordOutputMessages(['I found 15 urgent emails', 'Here is your organized inbox']); - -} catch (error) { - scope.recordError(error as Error); - throw error; -} -// Scope automatically disposed at end of using block -``` - -### 2. Execute Tool Spans - -Track tool executions and function calls with endpoint support: - -```typescript -import { ExecuteToolScope } from '@microsoft/agents-a365-observability'; - -const toolDetails = { - toolName: 'email-search', - arguments: JSON.stringify({ query: 'from:boss@company.com', limit: 10 }), - toolCallId: 'tool-call-456', - description: 'Search emails by criteria', - toolType: 'function', - endpoint: { - host: 'tools.contoso.com', - port: 8080, // Will be recorded since not 443 - protocol: 'https' - } -}; - -using scope = ExecuteToolScope.start(toolDetails, agentDetails, tenantDetails); - -try { - // Execute the tool - const result = await searchEmails(toolDetails.arguments); - - // Record the tool execution result - scope.recordResponse(JSON.stringify(result)); - - return result; -} catch (error) { - scope.recordError(error as Error); - throw error; -} -``` - -### 3. Inference Call Spans - -Track LLM/AI model inference calls with enhanced telemetry methods: - -```typescript -import { InferenceScope, InferenceOperationType } from '@microsoft/agents-a365-observability'; - -const inferenceDetails = { - operationName: InferenceOperationType.CHAT, - model: 'gpt-4', - providerName: 'openai', - inputTokens: 150, - outputTokens: 75, - finishReasons: ['stop'], - responseId: 'resp-123456' -}; - -using scope = InferenceScope.start(inferenceDetails, agentDetails, tenantDetails); - -try { - // Record input messages - scope.recordInputMessages(['Summarize the following emails for me...']); - - // Call the LLM - const response = await callLLM(); - - // Record detailed telemetry with granular methods - scope.recordOutputMessages(['Here is your email summary...']); - scope.recordInputTokens(145); // Update if different from constructor - scope.recordOutputTokens(82); // Update if different from constructor - scope.recordResponseId('resp-789123'); - scope.recordFinishReasons(['stop', 'max_tokens']); - - return response.text; -} catch (error) { - scope.recordError(error as Error); - throw error; -} -``` - -#### Available Methods for Inference Scope: - -- `recordInputMessages(messages: string[])` - Record input message array -- `recordOutputMessages(messages: string[])` - Record output message array -- `recordInputTokens(inputTokens: number)` - Record input token count -- `recordOutputTokens(outputTokens: number)` - Record output token count -- `recordResponseId(responseId: string)` - Record response ID with validation -- `recordFinishReasons(finishReasons: string[])` - Record finish reasons array - -## 🧳 Baggage Usage - -Baggage enables context propagation across distributed agent systems. Use the `BaggageBuilder` to set contextual information that flows through all spans in a request: - -### Basic Baggage Usage - -```typescript -import { BaggageBuilder } from '@microsoft/agents-a365-observability'; - -// Create and apply baggage context -using baggageScope = new BaggageBuilder() - // Core identifiers - .tenantId('tenant-123') - .agentId('agent-456') - .correlationId('correlation-789') - - // Agent information - .agentName('Email Assistant') - .agentDescription('AI assistant for email management') - .agentAuid('auid-123') // Agent User ID - .agentUpn('agent@company.com') - .agentBlueprintId('blueprint-456') - - // Caller information - .callerId('user-789') - .callerName('Jane Smith') - .callerUpn('jane.smith@company.com') - - // Conversation context - .conversationId('conv-123') - .conversationItemLink('https://teams.microsoft.com/...') - - // Source metadata (e.g., Teams channel) - .sourceMetadataId('channel-123') - .sourceMetadataName('msteams') - .sourceMetadataDescription('Main team channel') - - // Operation context - .operationSource('sdk') - .hiringManagerId('manager-456') - .build(); - -// Execute operations within the baggage context -baggageScope.run(() => { - // All spans created within this context will inherit the baggage values - - // Invoke another agent - using agentScope = InvokeAgentScope.start(invokeDetails, agentDetails, tenantDetails); - // ... agent logic - - // Execute tools - using toolScope = ExecuteToolScope.start(toolDetails, agentDetails, tenantDetails); - // ... tool logic -}); -``` - -## � Enhanced Interfaces - -### CallerDetails Interface -For tracking non-agent callers (human users): - -```typescript -interface CallerDetails { - callerId?: string; - callerName?: string; - callerUpn?: string; - callerUserId?: string; - tenantId?: string; -} -``` - -### EnhancedAgentDetails Interface -For tracking caller agent information in agent-to-agent calls: - -```typescript -interface EnhancedAgentDetails extends AgentDetails { - agentAUID?: string; // Agent User ID - agentUPN?: string; // Agent User Principal Name - agentBlueprintId?: string; // Agent Blueprint/Application ID - tenantId?: string; // Agent tenant ID -} -``` - -### ServiceEndpoint Interface -For endpoint information in tool calls and agent invocations: - -```typescript -interface ServiceEndpoint { - host: string; - port?: number; // Defaults to 443 for HTTPS - protocol?: string; // http or https -} -``` - -## �🔧 Advanced Usage - -### Enhanced Agent Invocation Methods - -InvokeAgentScope provides methods for recording detailed message arrays and responses: - -```typescript -using scope = InvokeAgentScope.start(invokeDetails, tenantDetails, callerAgentDetails, callerDetails); - -// Record multiple input messages -scope.recordInputMessages([ - 'Please analyze my email traffic', - 'Focus on the last 7 days', - 'Include sender statistics' -]); - -// Record multiple output messages -scope.recordOutputMessages([ - 'Analysis complete', - 'Found 147 emails from 23 unique senders', - 'Most active sender: boss@company.com (45 emails)' -]); -``` - -### Granular Inference Telemetry +## Usage -InferenceScope supports detailed telemetry recording: +For detailed usage examples and implementation guidance, see the [Microsoft Agent 365 Observability Documentation](https://learn.microsoft.com/microsoft-agent-365/developer/observability?tabs=nodejs). -```typescript -using scope = InferenceScope.start(inferenceDetails, agentDetails, tenantDetails); +## Support -// Record tokens separately -scope.recordInputTokens(250); -scope.recordOutputTokens(180); +For issues, questions, or feedback: -// Record response metadata -scope.recordResponseId('chat-resp-456789'); -scope.recordFinishReasons(['stop', 'length']); +- File issues in the [GitHub Issues](https://github.com/microsoft/Agent365-nodejs/issues) section +- See the [main documentation](../../README.md) for more information -// Record message arrays -scope.recordInputMessages(['System prompt', 'User message']); -scope.recordOutputMessages(['Assistant response']); -``` - -### Manual Scope Management - -If you prefer manual disposal over `using` declarations: +## 📋 Telemetry -```typescript -const scope = InvokeAgentScope.start(invokeDetails, tenantDetails, callerAgentDetails, callerDetails); +Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. -try { - // Your logic here - const result = await processRequest(); - scope.recordOutputMessages([result]); -} catch (error) { - scope.recordError(error as Error); - throw error; -} finally { - scope.dispose(); // Manual cleanup -} -``` - -### Error Handling and Recording +## Trademarks -```typescript -using scope = ExecuteToolScope.start(toolDetails, agentDetails, tenantDetails); +*Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* -try { - const result = await executeTool(); - scope.recordResponse(JSON.stringify(result)); -} catch (error) { - // Record detailed error information - scope.recordError(error as Error); - - throw error; // Re-throw to maintain error flow -} -``` +## License -### Shutdown and Cleanup +Copyright (c) Microsoft Corporation. All rights reserved. -```typescript -// Graceful shutdown -await ObservabilityManager.shutdown(); -``` \ No newline at end of file +Licensed under the MIT License - see the [LICENSE](../../LICENSE.md) file for details diff --git a/packages/agents-a365-runtime/README.md b/packages/agents-a365-runtime/README.md index 11ba2c2c..bf7cd0ab 100644 --- a/packages/agents-a365-runtime/README.md +++ b/packages/agents-a365-runtime/README.md @@ -1,27 +1,37 @@ # @microsoft/agents-a365-runtime -Agent 365 Runtime SDK for AI agents built with TypeScript/Node.js. +[![npm](https://img.shields.io/npm/v/@microsoft/agents-a365-runtime?label=npm&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-runtime) +[![npm Downloads](https://img.shields.io/npm/dm/@microsoft/agents-a365-runtime?label=Downloads&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-runtime) -## Description - -This package provides runtime utilities and services for Agent365 SDK, including: -- Agentic Authentication Service -- Agentic Authorization Service -- Power Platform API Discovery -- Semaphore utilities +Core runtime utilities and services for applications built with the Microsoft Agent 365 SDK. This package provides authentication, authorization, and Power Platform API discovery capabilities for building enterprise-ready AI agents. ## Installation -\\\ash +```bash npm install @microsoft/agents-a365-runtime -\\\ +``` ## Usage -\\\ ypescript -import { AgenticAuthenticationService, AgenticAuthorizationService } from '@microsoft/agents-a365-runtime'; -\\\ +For detailed usage examples and implementation guidance, see the [Microsoft Agent 365 Developer Documentation](https://learn.microsoft.com/microsoft-agent-365/developer/?tabs=nodejs). + +## Support + +For issues, questions, or feedback: + +- File issues in the [GitHub Issues](https://github.com/microsoft/Agent365-nodejs/issues) section +- See the [main documentation](../../README.md) for more information + +## 📋 Telemetry + +Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. + +## Trademarks + +*Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* ## License -See license file +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the MIT License - see the [LICENSE](../../LICENSE.md) file for details diff --git a/packages/agents-a365-tooling-extensions-claude/README.md b/packages/agents-a365-tooling-extensions-claude/README.md index 50a982c2..c808bea2 100644 --- a/packages/agents-a365-tooling-extensions-claude/README.md +++ b/packages/agents-a365-tooling-extensions-claude/README.md @@ -1,183 +1,37 @@ -# Agent 365 Node.js Claude Tooling SDK +# @microsoft/agents-a365-tooling-extensions-claude -This package provides TypeScript/Node.js support for integrating Microsoft Agent365 tooling with Claude SDK, enabling seamless access to MCP servers. +[![npm](https://img.shields.io/npm/v/@microsoft/agents-a365-tooling-extensions-claude?label=npm&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-tooling-extensions-claude) +[![npm Downloads](https://img.shields.io/npm/dm/@microsoft/agents-a365-tooling-extensions-claude?label=Downloads&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-tooling-extensions-claude) -The package name is **@microsoft/agents-a365-tooling-extensions-claude** +Claude SDK integration for the Microsoft Agent 365 Tooling SDK. This package enables seamless integration of MCP (Model Context Protocol) tool servers with Anthropic's Claude, providing automatic tool discovery and registration. ## Installation -This package is part of the `@microsoft/agent365-sdk` workspace and is typically installed as a dependency: - ```bash npm install @microsoft/agents-a365-tooling-extensions-claude ``` -## Core Components - -### `McpToolRegistrationService` - -The main service class that handles MCP server discovery and tool registration for Claude. - -```typescript -import { McpToolRegistrationService } from '@microsoft/agents-a365-tooling-extensions-claude'; - -const toolService = new McpToolRegistrationService(); -``` - ## Usage -### 1. Basic Tool Server Registration - -Register all available MCP tool servers with Claude options: - -```typescript -import { query, Options } from '@anthropic-ai/claude-code'; -import { McpToolRegistrationService } from '@microsoft/agents-a365-tooling-extensions-claude'; -import { AgentApplication } from '@microsoft/agents-hosting'; - -const app = new AgentApplication(); - -const agentOptions: Options = { - appendSystemPrompt: `You are a helpful AI assistant integrated with Microsoft 365.`, - maxTurns: 3, - allowedTools: ['Read', 'Write', 'WebSearch', 'Bash', 'Grep'], -}; - -const toolService = new McpToolRegistrationService(); - -await toolService.addToolServers( - agentOptions, - process.env.AGENTIC_USER_ID || '', - app.authorization, - turnContext, - process.env.MCP_AUTH_TOKEN || '' -); -``` - -### 2. Complete Agent Setup with Tools - -```typescript -import { query, Options } from '@anthropic-ai/claude-code'; -import { McpToolRegistrationService } from '@microsoft/agents-a365-tooling-extensions-claude'; - -async function invokeAgent(userMessage: string): Promise { - let claudeResponse = ""; - try { - for await (const message of query({ - prompt: userMessage, - options: agentOptions - })) { - if (message.type === 'result' && message.result) { - claudeResponse = message.result; - break; - } - } - if (!claudeResponse) { - return "Sorry, I couldn't get a response from Claude :("; - } - return claudeResponse; - } catch (error) { - console.error('Claude query error:', error); - return `Error: ${error.message || error}`; - } -} -``` - -### 3. Tool Discovery and Inspection - -List available tools from registered MCP servers: - -```typescript -import { McpServerConfig } from '@anthropic-ai/claude-code'; -import { McpToolRegistrationService } from '@microsoft/agents-a365-tooling-extensions-claude'; +For detailed usage examples and implementation guidance, see the [Microsoft Agent 365 Tooling Documentation](https://learn.microsoft.com/microsoft-agent-365/developer/tooling?tabs=nodejs). -const toolService = new McpToolRegistrationService(); - -// Create MCP server configuration -const mcpServerConfig: McpServerConfig = { - type: 'http', - url: 'https://your-mcp-server.com', - headers: { - 'Authorization': `Bearer ${authToken}`, - } -}; - -// Get available tools -const tools = await toolService.getTools('MyToolServer', mcpServerConfig); -console.log('Available tools:', tools); -``` - -## Configuration - -### Environment Variables - -The following environment variables are commonly used: - -```bash -# Agent365 Authentication -AGENTIC_USER_ID=your-user-id -MCP_AUTH_TOKEN=your-auth-token - -# Agent Configuration -AGENT_ID=your-agent-id -``` - -### Authentication Options - -The SDK supports multiple authentication methods: - -1. **Agent365 Authentication** (Recommended for production) - ```typescript - // Uses authorization and turnContext for token acquisition - await toolService.addToolServers( - agentOptions, - userId, - authorization, - turnContext, - '' // Empty auth token - will be acquired automatically - ); - ``` - -2. **Direct Token Authentication** - ```typescript - // Uses provided MCP_AUTH_TOKEN - await toolService.addToolServers( - agentOptions, - userId, - authorization, - turnContext, - process.env.MCP_AUTH_TOKEN - ); - ``` +## Support -## Complete Example +For issues, questions, or feedback: -See the complete working example in [`/nodejs/samples/claude-code-sdk/`](../../../samples/claude-code-sdk/) which demonstrates: +- File issues in the [GitHub Issues](https://github.com/microsoft/Agent365-nodejs/issues) section +- See the [main documentation](../../README.md) for more information -- Full agent setup with MCP tool registration -- Agent365 notification handling (email and Word comments) -- Observability integration -- Error handling and lifecycle management +## 📋 Telemetry -## Dependencies +Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. -This package depends on: +## Trademarks -- `@anthropic-ai/claude-code` - Claude SDK -- `@microsoft/agents-hosting` - Agent365 hosting framework -- `@microsoft/agents-a365-tooling` - Common tooling functionality -- `@microsoft/agents-a365-runtime` - Agent365 runtime services +*Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* ## License -See the main repository license file. - -## Contributing - -Contributions are welcome! Please see the main repository for contribution guidelines. - -## Support +Copyright (c) Microsoft Corporation. All rights reserved. -- **Issues**: Report bugs and request features through GitHub Issues -- **Documentation**: Additional documentation available in the main repository -- **Samples**: Working examples in `/nodejs/samples/claude-code-sdk/` +Licensed under the MIT License - see the [LICENSE](../../LICENSE.md) file for details diff --git a/packages/agents-a365-tooling-extensions-langchain/README.md b/packages/agents-a365-tooling-extensions-langchain/README.md index 36e41e37..058f950e 100644 --- a/packages/agents-a365-tooling-extensions-langchain/README.md +++ b/packages/agents-a365-tooling-extensions-langchain/README.md @@ -1,209 +1,37 @@ -# Agent 365 Node.js LangChain Tooling SDK +# @microsoft/agents-a365-tooling-extensions-langchain -This package provides TypeScript/Node.js support for integrating Microsoft Agent365 tooling with LangChain, enabling seamless access to MCP servers and tools within LangChain-based AI agents. +[![npm](https://img.shields.io/npm/v/@microsoft/agents-a365-tooling-extensions-langchain?label=npm&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-tooling-extensions-langchain) +[![npm Downloads](https://img.shields.io/npm/dm/@microsoft/agents-a365-tooling-extensions-langchain?label=Downloads&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-tooling-extensions-langchain) -The package name is **@microsoft/agents-a365-tooling-extensions-langchain** +LangChain integration for the Microsoft Agent 365 Tooling SDK. This package enables seamless integration of MCP (Model Context Protocol) tool servers with LangChain agents, providing automatic tool discovery and registration as DynamicStructuredTool instances. ## Installation -This package is part of the `@microsoft/agent365-sdk` workspace and is typically installed as a dependency: - ```bash npm install @microsoft/agents-a365-tooling-extensions-langchain ``` -## Core Components - -### `McpToolRegistrationService` - -The main service class that handles MCP server discovery and tool registration for LangChain agents. It converts MCP tools into LangChain-compatible `DynamicStructuredTool` instances. - -```typescript -import { McpToolRegistrationService } from '@microsoft/agents-a365-tooling-extensions-langchain'; - -const toolService = new McpToolRegistrationService(); -``` - ## Usage -### 1. Basic Tool Server Registration - -Register all available MCP tool servers with LangChain client configuration: - -```typescript -import { createReactAgent } from "@langchain/langgraph/prebuilt"; -import { ChatOpenAI } from "@langchain/openai"; -import { McpToolRegistrationService } from '@microsoft/agents-a365-tooling-extensions-langchain'; -import { ClientConfig } from '@langchain/mcp-adapters'; -import { Authorization, TurnContext } from '@microsoft/agents-hosting'; - -const toolService = new McpToolRegistrationService(); - -// Configure MCP client -const mcpClientConfig = {} as ClientConfig; - -// Add MCP tool servers and get LangChain tools -const tools = await toolService.addMcpToolServers( - mcpClientConfig, - process.env.AGENTIC_USER_ID || '', - authorization, - turnContext, - process.env.MCP_AUTH_TOKEN || '' -); - -// Create the model -const model = new ChatOpenAI({ - model: "gpt-4o-mini", -}); - -// Create the agent with MCP tools -const agent = createReactAgent({ - llm: model, - tools: tools, - name: 'LangChain Agent', - includeAgentName: 'inline' -}); -``` - -### 2. Complete Agent Setup with Agent365 Integration - -```typescript -async function invokeAgent(userMessage: string): Promise { - try { - const result = await agent.invoke({ - messages: [ - { - role: "user", - content: userMessage, - }, - ], - }); - - let agentMessage = ''; - - // Extract the content from the LangChain response - if (result.messages && result.messages.length > 0) { - const lastMessage = result.messages[result.messages.length - 1]; - agentMessage = lastMessage.content || "No content in response"; - } - - // Fallback if result is already a string - if (typeof result === 'string') { - agentMessage = result; - } - - if (!agentMessage) { - return "Sorry, I couldn't get a response from the agent :("; - } - - return agentMessage; - } catch (error) { - console.error('LangChain agent error:', error); - const err = error as any; - return `Error: ${err.message || err}`; - } -} -``` - -### 3. Tool Discovery and Inspection - -List available tools from registered MCP servers: +For detailed usage examples and implementation guidance, see the [Microsoft Agent 365 Tooling Documentation](https://learn.microsoft.com/microsoft-agent-365/developer/tooling?tabs=nodejs). -```typescript -import { Connection } from '@langchain/mcp-adapters'; -import { McpToolRegistrationService } from '@microsoft/agents-a365-tooling-extensions-langchain'; - -const toolService = new McpToolRegistrationService(); - -// Create MCP server connection -const mcpServerName = 'MyMCPServer'; -const mcpServerConnection: Connection = { - type: 'http', - url: 'https://your-mcp-server.com', - headers: { - 'Authorization': `Bearer ${authToken}`, - } -}; +## Support -// Get available tools -const tools = await toolService.getTools(mcpServerName, mcpServerConnection); -console.log('Available tools:', tools); -``` +For issues, questions, or feedback: -## Configuration +- File issues in the [GitHub Issues](https://github.com/microsoft/Agent365-nodejs/issues) section +- See the [main documentation](../../README.md) for more information -### Environment Variables +## 📋 Telemetry -The following environment variables are commonly used: +Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. -```bash -# Agent365 Authentication -AGENTIC_USER_ID=your-user-id -MCP_AUTH_TOKEN=your-auth-token +## Trademarks -# Agent Configuration -AGENT_ID=your-agent-id -``` - -### Authentication Options - -The SDK supports multiple authentication methods: - -1. **Agent365 Authentication** (Recommended for production) - ```typescript - // Uses authorization and turnContext for token acquisition - await toolService.addMcpToolServers( - mcpClientConfig, - userId, - authorization, - turnContext, - '' // Empty auth token - will be acquired automatically - ); - ``` - -2. **Direct Token Authentication** - ```typescript - // Uses provided MCP_AUTH_TOKEN - await toolService.addMcpToolServers( - mcpClientConfig, - userId, - authorization, - turnContext, - process.env.MCP_AUTH_TOKEN - ); - ``` - -## Complete Example - -See the complete working example in [`/nodejs/samples/langchain-sample/`](../../../samples/langchain-sample/) which demonstrates: - -- Full agent setup with MCP tool registration -- LangChain React agent creation with Agent365 tools -- Agent365 notification handling (email and Word comments) -- Observability integration with tracing -- Error handling and lifecycle management -- Express.js hosting integration - -## Dependencies - -This package depends on: - -- `@langchain/core` - LangChain core functionality -- `@langchain/mcp-adapters` - LangChain MCP adapters -- `@microsoft/agents-hosting` - Agent365 hosting framework -- `@microsoft/agents-a365-tooling` - Common tooling functionality -- `@microsoft/agents-a365-runtime` - Agent365 runtime services +*Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* ## License -See the main repository license file. - -## Contributing - -Contributions are welcome! Please see the main repository for contribution guidelines. - -## Support +Copyright (c) Microsoft Corporation. All rights reserved. -- **Issues**: Report bugs and request features through GitHub Issues -- **Documentation**: Additional documentation available in the main repository -- **Samples**: Working examples in `/nodejs/samples/langchain-sample/` +Licensed under the MIT License - see the [LICENSE](../../LICENSE.md) file for details diff --git a/packages/agents-a365-tooling-extensions-openai/README.md b/packages/agents-a365-tooling-extensions-openai/README.md index 2bb484d2..384f435e 100644 --- a/packages/agents-a365-tooling-extensions-openai/README.md +++ b/packages/agents-a365-tooling-extensions-openai/README.md @@ -1,195 +1,37 @@ -````markdown -# Agent 365 Node.js OpenAI Tooling SDK +# @microsoft/agents-a365-tooling-extensions-openai -This package provides TypeScript/Node.js support for integrating Microsoft Agent365 tooling with OpenAI Agents SDK, enabling seamless access to MCP servers. +[![npm](https://img.shields.io/npm/v/@microsoft/agents-a365-tooling-extensions-openai?label=npm&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-tooling-extensions-openai) +[![npm Downloads](https://img.shields.io/npm/dm/@microsoft/agents-a365-tooling-extensions-openai?label=Downloads&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-tooling-extensions-openai) -The package name is **@microsoft/agents-a365-tooling-extensions-openai** +OpenAI Agents SDK integration for the Microsoft Agent 365 Tooling SDK. This package enables seamless integration of MCP (Model Context Protocol) tool servers with OpenAI Agents, providing automatic tool discovery and registration. ## Installation -This package is part of the `@microsoft/agent365-sdk` workspace and is typically installed as a dependency: - ```bash npm install @microsoft/agents-a365-tooling-extensions-openai ``` -## Core Components - -### `McpToolRegistrationService` - -The main service class that handles MCP server discovery and tool registration for OpenAI Agents. - -```typescript -import { McpToolRegistrationService } from '@microsoft/agents-a365-tooling-extensions-openai'; - -const toolService = new McpToolRegistrationService(); -``` - ## Usage -### 1. Basic Tool Server Registration - -Register all available MCP tool servers with an OpenAI Agent: - -```typescript -import { Agent } from '@openai/agents'; -import { McpToolRegistrationService } from '@microsoft/agents-a365-tooling-extensions-openai'; - -const agent = new Agent({ - name: 'My Agent', - // Other agent configuration -}); - -const toolService = new McpToolRegistrationService(); - -await toolService.addMcpToolServers( - agent, - process.env.AGENTIC_USER_ID || '', - authorization, - turnContext, - process.env.MCP_AUTH_TOKEN || '' -); -``` - -### 2. Complete Agent Setup with Tools - -```typescript -import { Agent, run } from '@openai/agents'; -import { McpToolRegistrationService } from '@microsoft/agents-a365-tooling-extensions-openai'; - -async function invokeAgent(userMessage: string): Promise { -try { - // Connect to MCP servers - await connectToServers(); - - // Run the agent with the user message - const result = await run(agent, userMessage); - return result.finalOutput || "Sorry, I couldn't process your request."; -} catch (error) { - console.error('OpenAI agent error:', error); - return `Error: ${error.message || error}`; -} finally { - // Clean up connections - await closeServers(); -} -} - -async function connectToServers(): Promise { -if (agent.mcpServers && agent.mcpServers.length > 0) { - for (const server of agent.mcpServers) { - await server.connect(); - } -} -} - -async function closeServers(): Promise { -if (agent.mcpServers && agent.mcpServers.length > 0) { - for (const server of agent.mcpServers) { - await server.close(); - } -} -} -``` - -### 3. Tool Discovery and Inspection - -List available tools from registered MCP servers: - -```typescript -import { MCPServerStreamableHttp } from '@openai/agents'; -import { McpToolRegistrationService } from '@microsoft/agents-a365-tooling-extensions-openai'; - -const toolService = new McpToolRegistrationService(); +For detailed usage examples and implementation guidance, see the [Microsoft Agent 365 Tooling Documentation](https://learn.microsoft.com/microsoft-agent-365/developer/tooling?tabs=nodejs). -// Create MCP server configuration -const mcpServer = new MCPServerStreamableHttp({ - url: 'https://your-mcp-server.com', - name: 'MyToolServer', - requestInit: { - headers: { - 'Authorization': `Bearer ${authToken}`, - } - } -}); - -// Get available tools -const tools = await toolService.getTools(mcpServer); -console.log('Available tools:', tools); -``` - -## Configuration - -### Environment Variables - -The following environment variables are commonly used: - -```bash -# Agent365 Authentication -AGENTIC_USER_ID=your-user-id -MCP_AUTH_TOKEN=your-auth-token - -# Agent Configuration -AGENT_ID=your-agent-id -``` - -### Authentication Options - -The SDK supports multiple authentication methods: - -1. **Agent365 Authentication** (Recommended for production) - ```typescript - // Uses authorization and turnContext for token acquisition - await toolService.addMcpToolServers( - agent, - userId, - authorization, - turnContext, - '' // Empty auth token - will be acquired automatically - ); - ``` - -2. **Direct Token Authentication** - ```typescript - // Uses provided MCP_AUTH_TOKEN - await toolService.addMcpToolServers( - agent, - userId, - authorization, - turnContext, - process.env.MCP_AUTH_TOKEN - ); - ``` +## Support -## Complete Example +For issues, questions, or feedback: -See the complete working example in [`/nodejs/samples/openai-agents-sdk/`](../../../samples/openai-agents-sdk/) which demonstrates: +- File issues in the [GitHub Issues](https://github.com/microsoft/Agent365-nodejs/issues) section +- See the [main documentation](../../README.md) for more information -- Full agent setup with MCP tool registration -- Agent365 notification handling (email and Word comments) -- Observability integration -- Error handling and lifecycle management +## 📋 Telemetry -## Dependencies +Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. -This package depends on: +## Trademarks -- `@openai/agents` - OpenAI Agents SDK -- `@microsoft/agents-hosting` - Agent365 hosting framework -- `@microsoft/agents-a365-tooling` - Common tooling functionality -- `@microsoft/agents-a365-runtime` - Agent365 runtime services +*Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* ## License -See the main repository license file. - -## Contributing - -Contributions are welcome! Please see the main repository for contribution guidelines. - -## Support - -- **Issues**: Report bugs and request features through GitHub Issues -- **Documentation**: Additional documentation available in the main repository -- **Samples**: Working examples in `/nodejs/samples/openai-agents-sdk/` +Copyright (c) Microsoft Corporation. All rights reserved. -```` \ No newline at end of file +Licensed under the MIT License - see the [LICENSE](../../LICENSE.md) file for details diff --git a/packages/agents-a365-tooling/README.md b/packages/agents-a365-tooling/README.md index e24c130c..1cda340c 100644 --- a/packages/agents-a365-tooling/README.md +++ b/packages/agents-a365-tooling/README.md @@ -1,158 +1,37 @@ -# Agent 365 Node.js Tooling SDK +# @microsoft/agents-a365-tooling -This directory contains the Node.js implementation of Agent 365 Tooling SDK for discovering and configuring MCP (Model Context Protocol) tool servers. +[![npm](https://img.shields.io/npm/v/@microsoft/agents-a365-tooling?label=npm&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-tooling) +[![npm Downloads](https://img.shields.io/npm/dm/@microsoft/agents-a365-tooling?label=Downloads&logo=npm)](https://www.npmjs.com/package/@microsoft/agents-a365-tooling) -The package name is **@microsoft/agents-a365-tooling** +Core tooling functionality for MCP (Model Context Protocol) tool server management in applications built with the Microsoft Agent 365 SDK. This package provides the foundation for discovering, registering, and managing tool servers across different AI frameworks. -## Features - -- **Automatic Server Discovery**: Discovers MCP tool servers in development and production environments -- **Environment-Aware Configuration**: Different behavior for development vs production environments -- **Flexible Tool Server Sources**: Supports local manifest files and remote tooling gateway -- **URL Generation**: Automatically builds proper MCP server URLs -- **Error Handling**: Comprehensive error handling and fallback mechanisms - -## Core Components - -### `McpToolServerConfigurationService` - -The main service for discovering and configuring MCP tool servers. - -### `Utility` - -Helper class for URL construction and environment detection. - -## How to Retrieve Agent 365 Tools - -### Basic Usage - -```typescript -import { McpToolServerConfigurationService } from '@microsoft/agents-a365-tooling'; - -const configService = new McpToolServerConfigurationService(); -const servers = await configService.listToolServers(agentUserId, authToken); -``` - -### Understanding Tool Server Discovery - -The `listToolServers` method uses different strategies based on your environment: - -#### Development Mode (`NODE_ENV=Development`) - -In development, the service reads from a local `ToolingManifest.json` file: - -1. **Primary Location**: `[ProjectRoot]/ToolingManifest.json` -2. **Fallback Location**: `[process.argv[1] directory]/ToolingManifest.json` - -#### Production Mode (any other NODE_ENV) - -In production, the service queries the remote tooling gateway using the provided agent user ID. - -## Configuration - -### Environment Variables - -Configure the service behavior using these environment variables: +## Installation ```bash -# Environment (determines discovery strategy) -NODE_ENV=Development|Test|Production - -# For development mode with MCP Platform -MCP_DEVELOPMENT_BASE_URL=https://agent365.svc.cloud.microsoft/mcp/environments - -# For development mode with mock servers -TOOLS_MODE=MockMCPServer -MOCK_MCP_SERVER_URL=http://localhost:5309/mcp-mock/agents/servers - -# For production environments -# No additional environment variables needed - uses default endpoints -``` - -### Development Setup with ToolingManifest.json - -Create a `ToolingManifest.json` file in your project root: - -```json -{ - "mcpServers": [ - { - "mcpServerName": "MailTools", - "mcpServerUniqueName": "mcp_MailTools" - }, - { - "mcpServerName": "CalendarTools", - "mcpServerUniqueName": "mcp_CalendarTools" - }, - { - "mcpServerName": "SharePointTools", - "mcpServerUniqueName": "mcp_SharePointTools" - }, - { - "mcpServerName": "OneDriveTools", - "mcpServerUniqueName": "mcp_OneDriveServer" - }, - { - "mcpServerName": "NLWeb", - "mcpServerUniqueName": "mcp_NLWeb" - } - ] -} +npm install @microsoft/agents-a365-tooling ``` -**Schema Explanation:** -- `mcpServerName`: Display name for the server (used in logs and debugging) -- `mcpServerUniqueName`: Unique identifier used to build the server URL +## Usage -### Production Setup with Tooling Gateway +For detailed usage examples and implementation guidance, see the [Microsoft Agent 365 Tooling Documentation](https://learn.microsoft.com/microsoft-agent-365/developer/tooling?tabs=nodejs). -For production environments, ensure you have: +## Support -1. **Valid Agent User ID**: The unique identifier for your digital worker/agent -2. **Authentication Token**: Bearer token for accessing the tooling gateway. +For issues, questions, or feedback: -```typescript -const agentUserId = process.env.AGENTIC_USER_ID || 'your-agent-user-id'; -const authToken = process.env.MCP_AUTH_TOKEN || await getAuthToken(); +- File issues in the [GitHub Issues](https://github.com/microsoft/Agent365-nodejs/issues) section +- See the [main documentation](../../README.md) for more information -const servers = await configService.listToolServers(agentUserId, authToken); -``` - -## Troubleshooting Tool Discovery - -### Common Issues and Solutions - -#### No Tools Found in Development - -**Problem**: `listToolServers` returns an empty array in development. - -**Solutions:** -- Verify `ToolingManifest.json` exists in your project root -- Check the JSON syntax is valid -- Ensure `NODE_ENV=Development` is set -- Check console warnings for file path issues - -```typescript -// Debug tool server discovery -const configService = new McpToolServerConfigurationService(); -console.log('Environment:', process.env.NODE_ENV); -console.log('Current working directory:', process.cwd()); - -const servers = await configService.listToolServers(agentUserId, authToken); -console.log('Discovered servers:', servers); -``` +## 📋 Telemetry -#### Invalid Server URLs +Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. -**Problem**: Generated URLs don't work or return 404 errors. +## Trademarks -**Solutions:** -- Check `mcpServerUniqueName` values in your manifest match available servers -- Ensure the environment's base URL is accessible +*Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* -## Integration Examples +## License -For complete working implementations, see: +Copyright (c) Microsoft Corporation. All rights reserved. -- **Claude Integration**: [`../Claude/McpToolRegistrationService.ts`](../Claude/McpToolRegistrationService.ts) -- **OpenAI Integration**: [`../OpenAI/McpToolRegistrationService.ts`](../OpenAI/McpToolRegistrationService.ts) +Licensed under the MIT License - see the [LICENSE](../../LICENSE.md) file for details diff --git a/tests-agent/basic-agent-sdk-sample/README.md b/tests-agent/basic-agent-sdk-sample/README.md index acaa2b84..8c5662d4 100644 --- a/tests-agent/basic-agent-sdk-sample/README.md +++ b/tests-agent/basic-agent-sdk-sample/README.md @@ -96,3 +96,17 @@ In the first terminal, where you are running the agent application, you should s ``` That means your agent is correctly receiving activities and correctly sending traces! + +## 📋 Telemetry + +Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. + +## Trademarks + +*Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* + +## License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the MIT License - see the [LICENSE](../../LICENSE.md) file for details. diff --git a/tests-agent/openai-agent-auto-instrument-sample/README.md b/tests-agent/openai-agent-auto-instrument-sample/README.md index 7b53ad88..2a55926d 100644 --- a/tests-agent/openai-agent-auto-instrument-sample/README.md +++ b/tests-agent/openai-agent-auto-instrument-sample/README.md @@ -176,3 +176,17 @@ Mail: ``` Error: 400 Invalid schema for function 'mcp_MailTools_graph_mail_createMessage': In context=('properties', 'toRecipients', 'items'), 'additionalProperties' is required to be supplied and to be false. ``` + +## 📋 Telemetry + +Data Collection. The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. + +## Trademarks + +*Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.* + +## License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the MIT License - see the [LICENSE](../../LICENSE.md) file for details.