@cuylabs/agent-a365-tooling 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,111 @@
1
+ # @cuylabs/agent-a365-tooling
2
+
3
+ Microsoft Agent 365 tooling adapter for `@cuylabs/agent-core`.
4
+
5
+ This package exposes one turn-scoped tool provider factory. On each chat turn,
6
+ it uses Microsoft's Agent 365 tooling SDK to discover MCP servers for the active
7
+ Microsoft 365 turn, connects those servers through agent-core's MCP manager,
8
+ and returns MCP tools for that turn only.
9
+
10
+ Use this when your agent is hosted behind Microsoft 365 / Agent 365 and should
11
+ use the MCP tool servers configured for the current tenant, user, and agent
12
+ identity. Do not use it for static MCP servers known at startup; use
13
+ `agent-core` MCP config for those.
14
+
15
+ ## What It Gives You
16
+
17
+ - Agent 365 MCP server discovery per Microsoft 365 turn.
18
+ - Microsoft SDK token exchange and per-server bearer headers.
19
+ - Agent 365 platform headers for real Microsoft-hosted MCP servers.
20
+ - Turn-scoped MCP tools that are cleaned up after the turn.
21
+ - A Microsoft-specific adapter without importing Microsoft SDK types into
22
+ `agent-core`.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ pnpm add @cuylabs/agent-a365-tooling @microsoft/agents-a365-tooling
28
+ ```
29
+
30
+ If you use the default ambient TurnContext lookup, also use
31
+ `@cuylabs/agent-channel-m365` and configure `@microsoft/agents-hosting` in the
32
+ host app.
33
+
34
+ ## Usage
35
+
36
+ ```ts
37
+ import { createAgent } from "@cuylabs/agent-core";
38
+ import { createA365ToolingTurnToolProvider } from "@cuylabs/agent-a365-tooling";
39
+
40
+ const agent = createAgent({
41
+ model,
42
+ turnToolProviders: [
43
+ createA365ToolingTurnToolProvider({
44
+ authorization,
45
+ authHandlerName: "agentic",
46
+ toolOptions: {
47
+ orchestratorName: "dory",
48
+ },
49
+ }),
50
+ ],
51
+ });
52
+ ```
53
+
54
+ By default the provider reads the active `TurnContext` from
55
+ `currentM365TurnContext()` in `@cuylabs/agent-channel-m365`. For tests or custom
56
+ hosts, pass `getTurnContext`.
57
+
58
+ ```ts
59
+ createA365ToolingTurnToolProvider({
60
+ authorization,
61
+ authHandlerName: "agentic",
62
+ getTurnContext: () => myTurnContext,
63
+ });
64
+ ```
65
+
66
+ ## Concept Docs
67
+
68
+ The package docs are split by concern:
69
+
70
+ | Doc | What it explains |
71
+ | --- | --- |
72
+ | [docs/architecture.md](./docs/architecture.md) | The four-layer split between agent-core, M365 channel ingress, Microsoft's A365 tooling SDK, and this adapter. |
73
+ | [docs/agent-core-mcp.md](./docs/agent-core-mcp.md) | How this package uses agent-core `turnToolProviders` and how that differs from static agent-core MCP config. |
74
+ | [docs/microsoft-a365-tooling.md](./docs/microsoft-a365-tooling.md) | What Microsoft's Agent 365 tooling SDK owns: discovery, dev manifest mode, gateway calls, and auth headers. |
75
+ | [docs/lifecycle-and-limits.md](./docs/lifecycle-and-limits.md) | Per-turn lifecycle, cleanup, latency, filtering, connector replacement, and v0 limits. |
76
+
77
+ Start with [docs/README.md](./docs/README.md) if you want the reading order.
78
+
79
+ ## Required Host Inputs
80
+
81
+ | Option | Meaning | Typical source |
82
+ | --- | --- | --- |
83
+ | `authorization` | Microsoft Agents SDK `Authorization` object used for token exchange | Your M365 host application / `@microsoft/agents-hosting` setup |
84
+ | `authHandlerName` | Name of the auth handler configured for Agent 365 token exchange | Your Microsoft Agents SDK app configuration |
85
+ | `getTurnContext` | Optional resolver for the active Microsoft `TurnContext` | Defaults to `@cuylabs/agent-channel-m365` ambient context |
86
+ | `authToken` | Optional pre-resolved gateway token | Local development or specialized hosts; normally omitted in production |
87
+ | `toolOptions` | Optional metadata such as `orchestratorName` | Host/application configuration |
88
+
89
+ In production, prefer omitting `authToken` so Microsoft's SDK performs token
90
+ exchange for the active turn. In local dev-manifest mode, examples can pass a
91
+ fake decoded token because the SDK reads `ToolingManifest.json` instead of
92
+ calling the cloud gateway.
93
+
94
+ ## What This Does Not Do
95
+
96
+ This package is not a channel, not an LLM provider, and not a replacement for
97
+ agent-core's MCP engine. It does not implement cross-turn MCP pooling,
98
+ mid-turn token refresh, or Agent 365 real-time threat protection chat-history
99
+ submission in v0.
100
+
101
+ ## Examples
102
+
103
+ Runnable examples live in the repository under
104
+ [`packages/agent-a365-tooling/examples`](https://github.com/cuylabs-ai/agents-ts/tree/main/packages/agent-a365-tooling/examples).
105
+ They are intentionally not included in the npm tarball because the example
106
+ `tsconfig.json` and `ToolingManifest.json` are monorepo-local development
107
+ harness files.
108
+
109
+ Start with `examples/01-dev-manifest.ts`; it uses Microsoft's local
110
+ `ToolingManifest.json` path and an in-process MCP fixture, so it verifies the
111
+ provider without Azure.
@@ -0,0 +1,132 @@
1
+ import { AgentTurnToolContext, Logger, AgentTurnToolProviderResult, MCPServerStatus, AgentTurnToolProvider, MCPConfig } from '@cuylabs/agent-core';
2
+
3
+ type MaybePromise<T> = T | Promise<T>;
4
+ type TurnMcpTools = NonNullable<AgentTurnToolProviderResult["mcpTools"]>;
5
+ type A365ToolingUtility = {
6
+ GetToolRequestHeaders?: (authToken?: string, turnContext?: A365TurnContextLike, options?: A365ToolingToolOptions) => Record<string, string>;
7
+ };
8
+ type A365TurnContextLike = {
9
+ activity?: unknown;
10
+ [key: string]: unknown;
11
+ };
12
+ type A365AuthorizationLike = object;
13
+ interface A365McpServerConfig {
14
+ mcpServerName: string;
15
+ url: string;
16
+ headers?: Record<string, string>;
17
+ audience?: string;
18
+ scope?: string;
19
+ publisher?: string;
20
+ }
21
+ interface A365ToolingToolOptions {
22
+ orchestratorName?: string;
23
+ [key: string]: unknown;
24
+ }
25
+ interface A365ToolingProviderContext {
26
+ agentContext: AgentTurnToolContext;
27
+ turnContext: A365TurnContextLike;
28
+ }
29
+ interface A365ToolingConnectorContext extends A365ToolingProviderContext {
30
+ providerName: string;
31
+ serverTimeoutMs: number;
32
+ logger?: Logger;
33
+ }
34
+ interface A365ToolingMcpConnection {
35
+ mcpTools: TurnMcpTools;
36
+ cleanup?: () => void | Promise<void>;
37
+ statuses?: Map<string, MCPServerStatus>;
38
+ }
39
+ type A365ToolingMcpConnector = (servers: A365McpServerConfig[], context: A365ToolingConnectorContext) => Promise<A365ToolingMcpConnection>;
40
+ type A365ToolingServerFilter = (servers: A365McpServerConfig[], context: A365ToolingProviderContext) => MaybePromise<A365McpServerConfig[]>;
41
+ type A365ToolingValueResolver<T> = (context: A365ToolingProviderContext) => MaybePromise<T>;
42
+ interface A365ToolingModule {
43
+ Utility?: A365ToolingUtility;
44
+ McpToolServerConfigurationService: new (configurationProvider?: unknown) => {
45
+ listToolServers(turnContext: A365TurnContextLike, authorization: A365AuthorizationLike, authHandlerName: string, authToken?: string, options?: A365ToolingToolOptions): Promise<A365McpServerConfig[]>;
46
+ };
47
+ }
48
+ interface CreateA365ToolingTurnToolProviderOptions {
49
+ /**
50
+ * Provider name used in duplicate-tool errors and logs.
51
+ *
52
+ * @default "a365-tooling"
53
+ */
54
+ name?: string;
55
+ /**
56
+ * Microsoft Agent 365 Authorization object, or a resolver for request-scoped
57
+ * Authorization. The concrete object comes from `@microsoft/agents-hosting`.
58
+ */
59
+ authorization: A365AuthorizationLike | A365ToolingValueResolver<A365AuthorizationLike>;
60
+ /**
61
+ * Auth handler name configured in the Microsoft Agents SDK application.
62
+ */
63
+ authHandlerName: string;
64
+ /**
65
+ * Optional bearer token for the A365 tooling gateway. Omit this in normal
66
+ * production use so Microsoft's SDK performs token exchange from the
67
+ * Authorization object and active TurnContext.
68
+ */
69
+ authToken?: string | A365ToolingValueResolver<string | undefined>;
70
+ /**
71
+ * Optional A365 tooling request options, such as `orchestratorName`.
72
+ */
73
+ toolOptions?: A365ToolingToolOptions | A365ToolingValueResolver<A365ToolingToolOptions | undefined>;
74
+ /**
75
+ * Gets the active Microsoft TurnContext.
76
+ *
77
+ * Defaults to reading `currentM365TurnContext()?.turnContext` from
78
+ * `@cuylabs/agent-channel-m365`. Pass this in tests or in hosts that bind
79
+ * TurnContext differently. Custom hosts should return a real Microsoft
80
+ * TurnContext or a compatible object with the activity fields required by
81
+ * Microsoft's A365 tooling SDK, including conversation and agent identity
82
+ * metadata.
83
+ */
84
+ getTurnContext?: () => MaybePromise<A365TurnContextLike | undefined>;
85
+ /**
86
+ * Optional Microsoft A365 tooling configuration provider.
87
+ */
88
+ configurationProvider?: unknown;
89
+ /**
90
+ * Optional server filter/gate before MCP connection.
91
+ *
92
+ * The input array is freshly resolved for the active turn. Returning a new
93
+ * array is recommended when filtering or reordering.
94
+ */
95
+ filterServers?: A365ToolingServerFilter;
96
+ /**
97
+ * Advanced connector override. The default connector creates one
98
+ * agent-core MCPManager per turn and closes it during turn cleanup.
99
+ */
100
+ connectMcpServers?: A365ToolingMcpConnector;
101
+ /**
102
+ * Test seam for loading `@microsoft/agents-a365-tooling`.
103
+ */
104
+ getToolingModule?: () => Promise<A365ToolingModule>;
105
+ /**
106
+ * Per-server MCP connect/list timeout.
107
+ *
108
+ * @default 5000
109
+ */
110
+ serverTimeoutMs?: number;
111
+ /**
112
+ * Reserved for future pooling modes. v0 supports per-turn connections only.
113
+ *
114
+ * @default "per-turn"
115
+ */
116
+ mode?: "per-turn";
117
+ logger?: Logger;
118
+ }
119
+ interface ToAgentCoreMcpConfigOptions {
120
+ timeoutMs?: number;
121
+ }
122
+ declare class A365ToolingTurnContextError extends Error {
123
+ constructor(message?: string, options?: ErrorOptions);
124
+ }
125
+ declare class A365ToolingModuleLoadError extends Error {
126
+ constructor(packageName: string, cause: unknown);
127
+ }
128
+ declare function createA365ToolingTurnToolProvider(options: CreateA365ToolingTurnToolProviderOptions): AgentTurnToolProvider;
129
+ declare function connectA365McpServers(servers: A365McpServerConfig[], context: A365ToolingConnectorContext): Promise<A365ToolingMcpConnection>;
130
+ declare function toAgentCoreMcpConfig(servers: A365McpServerConfig[], options?: ToAgentCoreMcpConfigOptions): MCPConfig;
131
+
132
+ export { type A365AuthorizationLike, type A365McpServerConfig, type A365ToolingConnectorContext, type A365ToolingMcpConnection, type A365ToolingMcpConnector, type A365ToolingModule, A365ToolingModuleLoadError, type A365ToolingProviderContext, type A365ToolingServerFilter, type A365ToolingToolOptions, A365ToolingTurnContextError, type A365ToolingValueResolver, type A365TurnContextLike, type CreateA365ToolingTurnToolProviderOptions, type ToAgentCoreMcpConfigOptions, connectA365McpServers, createA365ToolingTurnToolProvider, toAgentCoreMcpConfig };
package/dist/index.js ADDED
@@ -0,0 +1,266 @@
1
+ // src/index.ts
2
+ import {
3
+ createMCPManager
4
+ } from "@cuylabs/agent-core";
5
+ var A365_TOOLING_PACKAGE = "@microsoft/agents-a365-tooling";
6
+ var M365_CHANNEL_PACKAGE = "@cuylabs/agent-channel-m365";
7
+ var DEFAULT_PROVIDER_NAME = "a365-tooling";
8
+ var DEFAULT_SERVER_TIMEOUT_MS = 5e3;
9
+ var A365ToolingTurnContextError = class extends Error {
10
+ constructor(message = defaultMissingTurnContextMessage(), options) {
11
+ super(message, options);
12
+ this.name = "A365ToolingTurnContextError";
13
+ }
14
+ };
15
+ var A365ToolingModuleLoadError = class extends Error {
16
+ constructor(packageName, cause) {
17
+ super(
18
+ `Unable to load ${packageName}. Install it in the host application before using @cuylabs/agent-a365-tooling.`,
19
+ { cause }
20
+ );
21
+ this.name = "A365ToolingModuleLoadError";
22
+ }
23
+ };
24
+ function createA365ToolingTurnToolProvider(options) {
25
+ const providerName = normalizeProviderName(options.name);
26
+ const authHandlerName = normalizeRequiredString(
27
+ options.authHandlerName,
28
+ "authHandlerName"
29
+ );
30
+ const serverTimeoutMs = normalizeTimeout(options.serverTimeoutMs);
31
+ return {
32
+ name: providerName,
33
+ async resolveTools(agentContext) {
34
+ const turnContext = await resolveTurnContext(options.getTurnContext);
35
+ const providerContext = {
36
+ agentContext,
37
+ turnContext
38
+ };
39
+ const module = await loadToolingModule(options.getToolingModule);
40
+ const authorization = await resolveValue(
41
+ options.authorization,
42
+ providerContext
43
+ );
44
+ const authToken = await resolveOptionalValue(
45
+ options.authToken,
46
+ providerContext
47
+ );
48
+ const toolOptions = await resolveOptionalValue(
49
+ options.toolOptions,
50
+ providerContext
51
+ );
52
+ const service = new module.McpToolServerConfigurationService(
53
+ options.configurationProvider
54
+ );
55
+ let servers = await service.listToolServers(
56
+ turnContext,
57
+ authorization,
58
+ authHandlerName,
59
+ authToken,
60
+ toolOptions
61
+ );
62
+ if (options.filterServers) {
63
+ servers = await options.filterServers(servers, providerContext);
64
+ }
65
+ servers = attachBaseMcpHeaders(
66
+ servers,
67
+ module,
68
+ turnContext,
69
+ authToken,
70
+ toolOptions
71
+ );
72
+ if (servers.length === 0) {
73
+ options.logger?.info("A365 tooling resolved no MCP servers", {
74
+ provider: providerName,
75
+ sessionId: agentContext.sessionId,
76
+ turnId: agentContext.turnId
77
+ });
78
+ return { mcpTools: {} };
79
+ }
80
+ const connector = options.connectMcpServers ?? connectA365McpServers;
81
+ const connection = await connector(servers, {
82
+ ...providerContext,
83
+ providerName,
84
+ serverTimeoutMs,
85
+ ...options.logger ? { logger: options.logger } : {}
86
+ });
87
+ logConnectionStatuses(options.logger, providerName, connection.statuses);
88
+ return {
89
+ mcpTools: connection.mcpTools,
90
+ ...connection.cleanup ? { cleanup: connection.cleanup } : {}
91
+ };
92
+ }
93
+ };
94
+ }
95
+ async function connectA365McpServers(servers, context) {
96
+ const manager = createMCPManager(
97
+ toAgentCoreMcpConfig(servers, { timeoutMs: context.serverTimeoutMs })
98
+ );
99
+ try {
100
+ const statuses = await manager.connect();
101
+ const mcpTools = await manager.getTools();
102
+ return {
103
+ mcpTools,
104
+ statuses,
105
+ cleanup: () => manager.close()
106
+ };
107
+ } catch (error) {
108
+ try {
109
+ await manager.close();
110
+ } catch (closeError) {
111
+ context.logger?.warn(
112
+ "A365 tooling MCP cleanup after connect failure failed",
113
+ {
114
+ provider: context.providerName,
115
+ error: closeError instanceof Error ? closeError : new Error(String(closeError))
116
+ }
117
+ );
118
+ }
119
+ throw error;
120
+ }
121
+ }
122
+ function toAgentCoreMcpConfig(servers, options = {}) {
123
+ const timeout = normalizeTimeout(options.timeoutMs);
124
+ const config = {};
125
+ for (const server of servers) {
126
+ const name = normalizeRequiredString(server.mcpServerName, "mcpServerName");
127
+ const url = normalizeRequiredString(server.url, `url for ${name}`);
128
+ if (config[name]) {
129
+ throw new Error(`Duplicate A365 MCP server name "${name}"`);
130
+ }
131
+ config[name] = {
132
+ transport: "http",
133
+ name,
134
+ url,
135
+ timeout,
136
+ ...server.headers ? { headers: { ...server.headers } } : {}
137
+ };
138
+ }
139
+ return config;
140
+ }
141
+ function attachBaseMcpHeaders(servers, module, turnContext, authToken, toolOptions) {
142
+ const getToolRequestHeaders = module.Utility?.GetToolRequestHeaders;
143
+ if (!getToolRequestHeaders) {
144
+ return servers;
145
+ }
146
+ return servers.map((server) => {
147
+ const baseHeaders = getToolRequestHeaders(
148
+ // listToolServers already attaches per-server bearer tokens. Reuse one
149
+ // for header derivation when the host did not provide a gateway token.
150
+ authToken ?? extractBearerToken(server.headers),
151
+ turnContext,
152
+ toolOptions
153
+ );
154
+ if (Object.keys(baseHeaders).length === 0) {
155
+ return server;
156
+ }
157
+ return {
158
+ ...server,
159
+ // Match Microsoft's framework extensions: base platform headers first,
160
+ // then server-specific headers so per-server Authorization wins.
161
+ headers: { ...baseHeaders, ...server.headers }
162
+ };
163
+ });
164
+ }
165
+ function extractBearerToken(headers) {
166
+ if (!headers) {
167
+ return void 0;
168
+ }
169
+ for (const [key, value] of Object.entries(headers)) {
170
+ if (key.toLowerCase() !== "authorization") {
171
+ continue;
172
+ }
173
+ const match = /^Bearer\s+(.+)$/i.exec(value.trim());
174
+ return match?.[1];
175
+ }
176
+ return void 0;
177
+ }
178
+ async function resolveTurnContext(getTurnContext) {
179
+ const turnContext = getTurnContext ? await getTurnContext() : await getDefaultM365TurnContext();
180
+ if (!turnContext) {
181
+ throw new A365ToolingTurnContextError();
182
+ }
183
+ return turnContext;
184
+ }
185
+ async function getDefaultM365TurnContext() {
186
+ let module;
187
+ try {
188
+ module = await import(M365_CHANNEL_PACKAGE);
189
+ } catch (error) {
190
+ if (isMissingModuleError(error, M365_CHANNEL_PACKAGE)) {
191
+ throw new A365ToolingTurnContextError(
192
+ defaultMissingChannelPackageMessage(),
193
+ { cause: error }
194
+ );
195
+ }
196
+ throw error;
197
+ }
198
+ return module.currentM365TurnContext?.()?.turnContext;
199
+ }
200
+ async function loadToolingModule(getToolingModule) {
201
+ try {
202
+ return getToolingModule ? await getToolingModule() : await import(A365_TOOLING_PACKAGE);
203
+ } catch (error) {
204
+ throw new A365ToolingModuleLoadError(A365_TOOLING_PACKAGE, error);
205
+ }
206
+ }
207
+ async function resolveValue(value, context) {
208
+ return typeof value === "function" ? value(context) : value;
209
+ }
210
+ async function resolveOptionalValue(value, context) {
211
+ if (value === void 0) {
212
+ return void 0;
213
+ }
214
+ return typeof value === "function" ? value(context) : value;
215
+ }
216
+ function normalizeProviderName(name) {
217
+ return normalizeRequiredString(name ?? DEFAULT_PROVIDER_NAME, "name");
218
+ }
219
+ function normalizeTimeout(timeoutMs) {
220
+ const timeout = timeoutMs ?? DEFAULT_SERVER_TIMEOUT_MS;
221
+ if (!Number.isFinite(timeout) || timeout <= 0) {
222
+ throw new Error("serverTimeoutMs must be a positive finite number");
223
+ }
224
+ return timeout;
225
+ }
226
+ function normalizeRequiredString(value, name) {
227
+ const trimmed = value?.trim();
228
+ if (!trimmed) {
229
+ throw new Error(`${name} must be a non-empty string`);
230
+ }
231
+ return trimmed;
232
+ }
233
+ function logConnectionStatuses(logger, providerName, statuses) {
234
+ if (!logger || !statuses) {
235
+ return;
236
+ }
237
+ for (const [serverName, status] of statuses) {
238
+ if (status.status === "error") {
239
+ logger.warn("A365 tooling MCP server failed to connect", {
240
+ provider: providerName,
241
+ serverName,
242
+ error: status.error
243
+ });
244
+ }
245
+ }
246
+ }
247
+ function defaultMissingTurnContextMessage() {
248
+ return "createA365ToolingTurnToolProvider: no ambient TurnContext. This provider must run inside an @cuylabs/agent-channel-m365 turn. For tests or custom hosts, pass options.getTurnContext.";
249
+ }
250
+ function defaultMissingChannelPackageMessage() {
251
+ return "createA365ToolingTurnToolProvider: @cuylabs/agent-channel-m365 is not installed. Install @cuylabs/agent-channel-m365 or pass options.getTurnContext.";
252
+ }
253
+ function isMissingModuleError(error, packageName) {
254
+ if (!(error instanceof Error)) {
255
+ return false;
256
+ }
257
+ const code = error.code;
258
+ return code === "ERR_MODULE_NOT_FOUND" && error.message.includes(packageName);
259
+ }
260
+ export {
261
+ A365ToolingModuleLoadError,
262
+ A365ToolingTurnContextError,
263
+ connectA365McpServers,
264
+ createA365ToolingTurnToolProvider,
265
+ toAgentCoreMcpConfig
266
+ };
package/docs/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # Agent 365 Tooling Docs
2
+
3
+ `@cuylabs/agent-a365-tooling` connects Microsoft Agent 365 tooling discovery to
4
+ agent-core's turn-scoped tool system.
5
+
6
+ Read these files in this order:
7
+
8
+ 1. [architecture.md](./architecture.md)
9
+ Explains the four-layer design and where this package fits.
10
+ 2. [agent-core-mcp.md](./agent-core-mcp.md)
11
+ Explains what agent-core exposes, what this package uses, and how this
12
+ differs from normal static MCP configuration.
13
+ 3. [microsoft-a365-tooling.md](./microsoft-a365-tooling.md)
14
+ Explains what Microsoft's Agent 365 tooling SDK does and which host inputs
15
+ it needs.
16
+ 4. [lifecycle-and-limits.md](./lifecycle-and-limits.md)
17
+ Explains per-turn lifecycle, cleanup, latency, filtering, and v0 limits.
18
+
19
+ The short version:
20
+
21
+ - agent-core owns the platform-neutral runtime, model loop, tool execution, and
22
+ MCP client manager.
23
+ - `agent-channel-m365` owns M365 Activity ingress and ambient `TurnContext`
24
+ binding.
25
+ - Microsoft's Agent 365 tooling SDK owns A365 MCP server discovery and token
26
+ attachment.
27
+ - this package turns those discovered A365 MCP servers into agent-core
28
+ turn-scoped MCP tools.
@@ -0,0 +1,117 @@
1
+ # Agent-Core MCP Integration
2
+
3
+ This package builds on two agent-core concepts:
4
+
5
+ - `turnToolProviders`
6
+ - `createMCPManager()`
7
+
8
+ It does not replace agent-core MCP. It uses agent-core MCP at turn time.
9
+
10
+ ## Turn Tool Providers
11
+
12
+ agent-core exposes `turnToolProviders` on `createAgent()`:
13
+
14
+ ```ts
15
+ const agent = createAgent({
16
+ model,
17
+ turnToolProviders: [provider],
18
+ });
19
+ ```
20
+
21
+ A provider is called at the start of each user turn with an
22
+ `AgentTurnToolContext`:
23
+
24
+ ```ts
25
+ {
26
+ sessionId,
27
+ turnId,
28
+ message,
29
+ cwd,
30
+ abort,
31
+ }
32
+ ```
33
+
34
+ The provider can return:
35
+
36
+ - `tools`: AI SDK-compatible tools for the current turn.
37
+ - `mcpTools`: MCP-backed AI SDK tools for the current turn.
38
+ - `cleanup`: a callback agent-core runs after the turn completes or fails.
39
+
40
+ Those tools are merged into the model loop for only the active turn. They are
41
+ not persisted on the agent and are not visible to other sessions or future
42
+ turns.
43
+
44
+ ## How This Package Uses Turn Tools
45
+
46
+ `createA365ToolingTurnToolProvider()` returns an agent-core
47
+ `AgentTurnToolProvider`.
48
+
49
+ On each turn it:
50
+
51
+ 1. reads the active M365 `TurnContext`;
52
+ 2. asks Microsoft's Agent 365 tooling SDK for MCP server configs;
53
+ 3. merges Microsoft base platform headers with each returned server's headers;
54
+ 4. maps those configs into agent-core MCP config;
55
+ 5. calls `createMCPManager()`;
56
+ 6. returns the MCP tools from `manager.getTools()`;
57
+ 7. returns `cleanup: () => manager.close()`.
58
+
59
+ ## Static MCP Config vs A365 Turn Tools
60
+
61
+ agent-core already supports static MCP configuration. Use static MCP when the
62
+ server list is known when the agent is created:
63
+
64
+ ```ts
65
+ const manager = createMCPManager({
66
+ search: {
67
+ transport: "http",
68
+ url: "https://example.com/mcp",
69
+ },
70
+ });
71
+ ```
72
+
73
+ Agent 365 tooling is different. The server list is resolved from the current
74
+ Microsoft turn and may depend on:
75
+
76
+ - tenant;
77
+ - user;
78
+ - agent identity;
79
+ - A365 gateway configuration;
80
+ - auth handler and token exchange state.
81
+
82
+ That makes it turn-scoped, not static.
83
+
84
+ Put another way: `agent-core/mcp` is the engine that connects and executes MCP
85
+ tools. It does not discover Agent 365 servers or perform Microsoft token
86
+ exchange. Microsoft's `@microsoft/agents-a365-tooling` package does that
87
+ platform-specific discovery/auth work, and this package adapts its output into
88
+ agent-core's MCP engine.
89
+
90
+ ## Tool Names
91
+
92
+ agent-core namespaces MCP tools by server name:
93
+
94
+ ```txt
95
+ <serverName>__<toolName>
96
+ ```
97
+
98
+ For example:
99
+
100
+ ```txt
101
+ mail__search_messages
102
+ calendar__create_event
103
+ ```
104
+
105
+ The server name comes from Microsoft's `mcpServerName` field.
106
+ The prefixing happens inside agent-core's MCP manager. This package only passes
107
+ the Microsoft server name through as the MCP server `name`.
108
+
109
+ ## Cleanup Semantics
110
+
111
+ agent-core runs turn-tool cleanup after `onChatEnd` middleware.
112
+
113
+ For the default connector, cleanup closes the per-turn MCP manager. That closes
114
+ the MCP clients opened for this turn.
115
+
116
+ Cleanup is best-effort across providers. agent-core attempts all cleanup
117
+ callbacks and logs cleanup errors instead of hiding the original turn result.
@@ -0,0 +1,61 @@
1
+ # Architecture
2
+
3
+ This package exists to keep agent-core platform-neutral while still allowing an
4
+ M365-hosted agent to receive Microsoft Agent 365 tools for the current turn.
5
+
6
+ ## Layer Split
7
+
8
+ | Layer | Owns | Does not own |
9
+ | --- | --- | --- |
10
+ | `@cuylabs/agent-core` | Agent runtime, model loop, tool execution, MCP client lifecycle, `turnToolProviders` | Microsoft channel objects, Azure auth, Agent 365 discovery |
11
+ | `@cuylabs/agent-channel-m365` | M365 Activity/CloudAdapter ingress and ambient `TurnContext` binding | Agent 365 MCP discovery or MCP client connection |
12
+ | `@microsoft/agents-a365-tooling` | Agent 365 tooling discovery, `ToolingManifest.json` dev mode, gateway calls, token exchange, per-server auth headers | agent-core tool registration or model-loop lifecycle |
13
+ | `@cuylabs/agent-a365-tooling` | Glue that resolves Agent 365 MCP servers for the current turn and exposes them as agent-core turn-scoped MCP tools | Chat transport, model provider, long-lived pooling, token refresh |
14
+
15
+ The important boundary is that agent-core never imports Microsoft hosting
16
+ types. Microsoft-specific request state stays in the channel and adapter
17
+ packages.
18
+
19
+ ## Turn Flow
20
+
21
+ At runtime, one user message flows like this:
22
+
23
+ 1. M365 channel receives an Activity.
24
+ 2. `@cuylabs/agent-channel-m365` binds the active Microsoft `TurnContext` in
25
+ AsyncLocalStorage.
26
+ 3. The host calls `agent.chat()` through the M365 adapter.
27
+ 4. agent-core starts the chat turn.
28
+ 5. agent-core calls this package's `AgentTurnToolProvider`.
29
+ 6. This package reads the active `TurnContext`.
30
+ 7. This package calls Microsoft's `McpToolServerConfigurationService`.
31
+ 8. Microsoft's SDK resolves Agent 365 MCP server configs from either:
32
+ `ToolingManifest.json` in development, or the Agent 365 tooling gateway in
33
+ production.
34
+ 9. This package optionally applies `filterServers`.
35
+ 10. This package connects the MCP servers through agent-core's MCP manager.
36
+ 11. agent-core exposes the resulting MCP tools to the model for this turn.
37
+ 12. After the turn, agent-core runs cleanup and closes the per-turn MCP
38
+ manager.
39
+
40
+ ## Why Not Put This In Agent-Core?
41
+
42
+ Agent 365 tooling has Microsoft-specific inputs:
43
+
44
+ - Microsoft `TurnContext`
45
+ - Microsoft Agents SDK `Authorization`
46
+ - `authHandlerName`
47
+ - OBO token exchange behavior
48
+ - Agent 365 MCP server metadata
49
+
50
+ Putting those concepts in agent-core would make core platform-specific. The
51
+ adapter package keeps that boundary clean.
52
+
53
+ ## Why Not Create A Generic Tooling Discovery Package?
54
+
55
+ This package intentionally does not extract a generic discovery abstraction
56
+ yet. The A365 path is specific to Microsoft turn state and token exchange. A
57
+ future Salesforce, Slack, or internal platform discovery adapter may need a
58
+ different shape.
59
+
60
+ The rule for now is simple: wait for a second real adapter before extracting a
61
+ shared abstraction.
@@ -0,0 +1,112 @@
1
+ # Lifecycle And Limits
2
+
3
+ This package is intentionally small for v0. It resolves Agent 365 MCP tools once
4
+ per turn and cleans them up when the turn ends.
5
+
6
+ ## Per-Turn Lifecycle
7
+
8
+ For each user message:
9
+
10
+ 1. agent-core starts a turn.
11
+ 2. this provider resolves the active M365 `TurnContext`.
12
+ 3. Microsoft's SDK resolves MCP server configs.
13
+ 4. this provider optionally filters those server configs.
14
+ 5. the default connector creates an agent-core MCP manager.
15
+ 6. the MCP manager connects the servers and lists tools.
16
+ 7. those tools are exposed to the model for the current turn.
17
+ 8. cleanup closes the MCP manager after the turn.
18
+
19
+ ## Filtering
20
+
21
+ Use `filterServers` to gate or subset discovered MCP servers before connection:
22
+
23
+ ```ts
24
+ createA365ToolingTurnToolProvider({
25
+ authorization,
26
+ authHandlerName: "agentic",
27
+ filterServers: (servers) =>
28
+ servers.filter((server) => server.mcpServerName.startsWith("soc_")),
29
+ });
30
+ ```
31
+
32
+ The input array is newly resolved for the active turn. Returning a new array is
33
+ recommended when filtering or reordering.
34
+
35
+ ## Connector Replacement
36
+
37
+ Use `connectMcpServers` to replace the default per-turn MCP connector.
38
+
39
+ That is the extension point for:
40
+
41
+ - connection pooling;
42
+ - custom token refresh;
43
+ - custom logging;
44
+ - custom partial-failure policy;
45
+ - per-tenant or per-user MCP client reuse.
46
+
47
+ The default connector does this:
48
+
49
+ ```txt
50
+ A365 server configs -> agent-core MCP config -> createMCPManager() -> getTools()
51
+ ```
52
+
53
+ and returns cleanup that closes the manager.
54
+
55
+ ## Latency
56
+
57
+ One turn performs one A365 tooling discovery round and one MCP connect round.
58
+ Expect overhead from:
59
+
60
+ - gateway token exchange;
61
+ - tooling gateway discovery;
62
+ - per-audience token exchange;
63
+ - MCP initialize/list handshakes.
64
+
65
+ For several MCP servers this can be noticeable. v0 does not pool clients.
66
+
67
+ ## Token TTL
68
+
69
+ Microsoft's SDK attaches bearer tokens to returned MCP server headers. The
70
+ default connector snapshots those headers into MCP clients at connect time.
71
+
72
+ Long-running turns may outlive bearer token TTL. v0 does not refresh MCP
73
+ Authorization headers mid-turn.
74
+
75
+ Future token refresh should live behind `connectMcpServers`, not in agent-core.
76
+
77
+ ## Cleanup
78
+
79
+ The default cleanup calls `manager.close()`.
80
+
81
+ There is no package-level close timeout in v0. If production deployments show
82
+ tail-latency spikes during turn cleanup, add a future `closeTimeoutMs` option to
83
+ the connector path.
84
+
85
+ ## Abort
86
+
87
+ `AgentTurnToolContext.abort` is passed to providers, but agent-core's MCP
88
+ manager does not currently accept an abort signal for connection setup.
89
+
90
+ If a user aborts while MCP servers are connecting, v0 waits for the active MCP
91
+ connect/list operation to finish or hit `serverTimeoutMs`.
92
+
93
+ ## Partial Failures
94
+
95
+ agent-core's MCP manager tolerates partial server failures. If one server fails
96
+ to connect, healthy servers can still provide tools.
97
+
98
+ The default per-server timeout is 5000 ms so one flaky server does not add the
99
+ default 30 second MCP timeout to every turn.
100
+
101
+ ## Not In V0
102
+
103
+ v0 does not include:
104
+
105
+ - cross-turn MCP client pooling;
106
+ - mid-turn token refresh;
107
+ - real-time threat protection chat-history submission;
108
+ - generic platform-neutral MCP discovery abstraction;
109
+ - dedicated cleanup timeout;
110
+ - custom telemetry events for per-server partial failure.
111
+
112
+ Those can be added later without changing agent-core's turn-tool contract.
@@ -0,0 +1,180 @@
1
+ # Microsoft Agent 365 Tooling SDK
2
+
3
+ This package delegates Agent 365 discovery and token work to Microsoft's
4
+ `@microsoft/agents-a365-tooling` SDK.
5
+
6
+ ## Why Microsoft Created It
7
+
8
+ Microsoft's package is part of the Agent 365 SDK surface for agents that run in
9
+ the Microsoft 365 / Agent 365 ecosystem.
10
+
11
+ It exists because Agent 365 tooling is not just "connect to this MCP URL." It
12
+ is a platform problem:
13
+
14
+ - discover which MCP tool servers are configured for a specific Agent 365
15
+ agent identity;
16
+ - support local development through `ToolingManifest.json`;
17
+ - query the Agent 365 tooling gateway in production;
18
+ - resolve the active agent identity from `TurnContext` and/or auth token
19
+ claims;
20
+ - perform token exchange through the Microsoft Agents SDK `Authorization`
21
+ object and `authHandlerName`;
22
+ - attach the correct per-server bearer token headers, including per-audience
23
+ tokens for newer server shapes;
24
+ - add platform headers such as channel ID, subchannel ID, user agent, and
25
+ agent ID;
26
+ - optionally send chat history to the MCP platform for real-time threat
27
+ protection.
28
+
29
+ That is why Microsoft named the package "tooling" rather than "mcp-client".
30
+ The MCP protocol client is only one piece. The package's main job is to bridge
31
+ Agent 365 platform state to MCP server configuration.
32
+
33
+ ## What The Microsoft SDK Answers
34
+
35
+ The SDK answers this question:
36
+
37
+ > For this Microsoft 365 agent turn, which Agent 365 MCP servers should this
38
+ > agent be able to use, and what headers are needed to call them?
39
+
40
+ The output shape this adapter needs is:
41
+
42
+ ```ts
43
+ {
44
+ mcpServerName: "mail",
45
+ url: "https://...",
46
+ headers: {
47
+ Authorization: "Bearer ..."
48
+ }
49
+ }
50
+ ```
51
+
52
+ That maps directly to agent-core's remote HTTP MCP config.
53
+
54
+ ## Production Mode
55
+
56
+ In production, Microsoft's SDK can:
57
+
58
+ - inspect the active `TurnContext`;
59
+ - resolve the agent identity;
60
+ - use the host `Authorization` object;
61
+ - use the configured `authHandlerName`;
62
+ - acquire tokens for Agent 365 tooling gateway calls;
63
+ - query the Agent 365 tooling gateway;
64
+ - attach per-audience bearer tokens to returned MCP server configs.
65
+
66
+ The normal production path should omit `authToken`:
67
+
68
+ ```ts
69
+ createA365ToolingTurnToolProvider({
70
+ authorization,
71
+ authHandlerName: "agentic",
72
+ });
73
+ ```
74
+
75
+ When `authToken` is omitted, Microsoft's SDK performs token exchange from the
76
+ active turn and host authorization setup.
77
+
78
+ The production discovery endpoint is shaped around the Agent 365 platform:
79
+
80
+ ```txt
81
+ GET https://agent365.svc.cloud.microsoft/agents/v2/{agenticAppId}/mcpServers
82
+ ```
83
+
84
+ The SDK also knows how to build direct MCP server URLs under the platform base
85
+ URL when a manifest entry does not provide a custom `url`.
86
+
87
+ When framework-specific Microsoft extensions connect MCP servers, they merge
88
+ base platform headers from `Utility.GetToolRequestHeaders()` with each returned
89
+ server's headers. This adapter follows the same shape before handing configs to
90
+ agent-core MCP:
91
+
92
+ ```txt
93
+ base platform headers -> server-specific headers
94
+ ```
95
+
96
+ That order matters because per-server `Authorization` headers returned by the
97
+ SDK should override any shared gateway token header.
98
+
99
+ ## Development Manifest Mode
100
+
101
+ When `NODE_ENV=development`, Microsoft's SDK reads `ToolingManifest.json`
102
+ instead of calling the cloud gateway.
103
+
104
+ That is useful for local examples and tests because it exercises the same
105
+ adapter path without requiring:
106
+
107
+ - Azure deployment;
108
+ - a live Agent 365 tenant;
109
+ - real OBO token exchange;
110
+ - a real Agent 365 gateway response.
111
+
112
+ The local example uses a minimal decoded token because the SDK still decodes an
113
+ agent identity, but it does not call the cloud gateway while using the manifest
114
+ path.
115
+
116
+ The manifest mode is the reason the examples can validate this adapter without
117
+ Azure: Microsoft's SDK still returns the same `MCPServerConfig[]` shape, and
118
+ this package still maps those configs into agent-core MCP.
119
+
120
+ ## Host Inputs
121
+
122
+ | Option | Meaning | Typical source |
123
+ | --- | --- | --- |
124
+ | `authorization` | Microsoft Agents SDK `Authorization` object used for token exchange | M365 host application / `@microsoft/agents-hosting` setup |
125
+ | `authHandlerName` | Name of the auth handler configured for Agent 365 token exchange | Microsoft Agents SDK app configuration |
126
+ | `getTurnContext` | Optional resolver for the active Microsoft `TurnContext` | Defaults to `@cuylabs/agent-channel-m365` ambient context |
127
+ | `authToken` | Optional pre-resolved gateway token | Local development or specialized hosts |
128
+ | `toolOptions` | Optional metadata such as `orchestratorName` | Host/application configuration |
129
+
130
+ ## Ambient TurnContext
131
+
132
+ By default, this package reads:
133
+
134
+ ```ts
135
+ currentM365TurnContext()?.turnContext
136
+ ```
137
+
138
+ from `@cuylabs/agent-channel-m365`.
139
+
140
+ That means the provider must run inside an M365 channel turn unless the host
141
+ passes `getTurnContext`.
142
+
143
+ For tests or non-standard hosts:
144
+
145
+ ```ts
146
+ createA365ToolingTurnToolProvider({
147
+ authorization,
148
+ authHandlerName: "agentic",
149
+ getTurnContext: () => myTurnContext,
150
+ });
151
+ ```
152
+
153
+ Custom hosts should return a real Microsoft `TurnContext` or a compatible
154
+ object with the activity fields Microsoft's SDK needs, including conversation
155
+ and agent identity metadata.
156
+
157
+ ## How This Differs From Agent-Core MCP
158
+
159
+ agent-core MCP starts after a server config is already known:
160
+
161
+ ```ts
162
+ {
163
+ transport: "http",
164
+ url: "https://...",
165
+ headers: { Authorization: "Bearer ..." },
166
+ }
167
+ ```
168
+
169
+ Microsoft's Agent 365 tooling SDK is what obtains that config for an Agent 365
170
+ turn. It determines the `url`, `mcpServerName`, and `headers` from Microsoft
171
+ platform state.
172
+
173
+ So the layering is:
174
+
175
+ ```txt
176
+ Microsoft Agent 365 platform
177
+ -> @microsoft/agents-a365-tooling discovers authorized MCP server configs
178
+ -> @cuylabs/agent-a365-tooling maps those configs to agent-core turn tools
179
+ -> agent-core/mcp connects and executes tools
180
+ ```
package/package.json ADDED
@@ -0,0 +1,77 @@
1
+ {
2
+ "name": "@cuylabs/agent-a365-tooling",
3
+ "version": "3.0.0",
4
+ "description": "Microsoft Agent 365 tooling adapter for @cuylabs/agent-core turn-scoped MCP tools",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "docs",
18
+ "README.md"
19
+ ],
20
+ "dependencies": {
21
+ "@cuylabs/agent-core": "^3.0.0"
22
+ },
23
+ "peerDependencies": {
24
+ "@microsoft/agents-a365-tooling": ">=0.2.0-preview.5 <1.0.0",
25
+ "@microsoft/agents-hosting": ">=1.4.0",
26
+ "@cuylabs/agent-channel-m365": "^3.0.0"
27
+ },
28
+ "peerDependenciesMeta": {
29
+ "@cuylabs/agent-channel-m365": {
30
+ "optional": true
31
+ },
32
+ "@microsoft/agents-hosting": {
33
+ "optional": true
34
+ }
35
+ },
36
+ "devDependencies": {
37
+ "@ai-sdk/openai": "4.0.0-beta.38",
38
+ "@modelcontextprotocol/sdk": "^1.26.0",
39
+ "@types/node": "^22.0.0",
40
+ "dotenv": "^17.2.3",
41
+ "tsup": "^8.0.0",
42
+ "tsx": "^4.21.0",
43
+ "typescript": "^5.7.0",
44
+ "vitest": "^4.0.18",
45
+ "zod": "^3.25.76 || ^4.1.8",
46
+ "@cuylabs/agent-channel-m365": "^3.0.0"
47
+ },
48
+ "keywords": [
49
+ "agent",
50
+ "microsoft",
51
+ "agent365",
52
+ "a365",
53
+ "mcp",
54
+ "tooling"
55
+ ],
56
+ "author": "cuylabs",
57
+ "license": "Apache-2.0",
58
+ "repository": {
59
+ "type": "git",
60
+ "url": "https://github.com/cuylabs-ai/agents-ts.git",
61
+ "directory": "packages/agent-a365-tooling"
62
+ },
63
+ "engines": {
64
+ "node": ">=20"
65
+ },
66
+ "publishConfig": {
67
+ "access": "public"
68
+ },
69
+ "scripts": {
70
+ "build": "tsup src/index.ts --format esm --dts --clean",
71
+ "dev": "tsup src/index.ts --format esm --dts --watch",
72
+ "typecheck": "tsc --noEmit",
73
+ "test": "vitest run",
74
+ "test:watch": "vitest",
75
+ "clean": "rm -rf dist"
76
+ }
77
+ }