Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions PUBLISHING.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ See the full list of Microsoft-controlled scopes: `@microsoft`, `@azure`,
| AgentMesh Copilot Governance | `@microsoft/agentmesh-copilot-governance` | `packages/agentmesh-integrations/copilot-governance` |
| AgentMesh Mastra | `@microsoft/agentmesh-mastra` | `packages/agentmesh-integrations/mastra-agentmesh` |
| AgentMesh API | `@microsoft/agentmesh-api` | `packages/agent-mesh/services/api` |
| AgentMesh MCP Governance | `@microsoft/agentmesh-mcp-governance` | `packages/agent-mesh/packages/mcp-governance` |
| AgentMesh MCP Proxy | `@microsoft/agentmesh-mcp-proxy` | `packages/agent-mesh/packages/mcp-proxy` |
| AgentMesh SDK | `@microsoft/agentmesh-sdk` | `packages/agent-mesh/sdks/typescript` |
| Agent OS Copilot Extension | `@microsoft/agent-os-copilot-extension` | `packages/agent-os/extensions/copilot` |
Expand Down
139 changes: 132 additions & 7 deletions packages/agent-mesh/sdks/typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,19 @@ Provides agent identity (Ed25519 DIDs), trust scoring, policy evaluation, hash-c
## Installation

```bash
npm install @agentmesh/sdk
npm install @microsoft/agentmesh-sdk
```

For MCP-only workloads, install the standalone governance package instead:

```bash
npm install @microsoft/agentmesh-mcp-governance
```

## Quick Start

```typescript
import { AgentMeshClient } from '@agentmesh/sdk';
import { AgentMeshClient } from '@microsoft/agentmesh-sdk';

const client = AgentMeshClient.create('my-agent', {
capabilities: ['data.read', 'data.write'],
Expand All @@ -44,7 +50,7 @@ console.log(client.audit.verify()); // true
Manage agent identities built on Ed25519 key pairs.

```typescript
import { AgentIdentity } from '@agentmesh/sdk';
import { AgentIdentity } from '@microsoft/agentmesh-sdk';

const identity = AgentIdentity.generate('agent-1', ['read']);
const signature = identity.sign(new TextEncoder().encode('hello'));
Expand All @@ -60,7 +66,7 @@ const restored = AgentIdentity.fromJSON(json);
Track and score trust for peer agents.

```typescript
import { TrustManager } from '@agentmesh/sdk';
import { TrustManager } from '@microsoft/agentmesh-sdk';

const tm = new TrustManager({ initialScore: 0.5, decayFactor: 0.95 });

Expand All @@ -76,7 +82,7 @@ const score = tm.getTrustScore('peer-1');
Rule-based policy evaluation with conditions and YAML support.

```typescript
import { PolicyEngine } from '@agentmesh/sdk';
import { PolicyEngine } from '@microsoft/agentmesh-sdk';

const engine = new PolicyEngine([
{ action: 'data.*', effect: 'allow' },
Expand All @@ -96,7 +102,7 @@ await engine.loadFromYAML('./policy.yaml');
Append-only audit log with hash-chain integrity verification.

```typescript
import { AuditLogger } from '@agentmesh/sdk';
import { AuditLogger } from '@microsoft/agentmesh-sdk';

const logger = new AuditLogger();

Expand All @@ -113,7 +119,7 @@ logger.exportJSON(); // full log as JSON string
Unified client tying identity, trust, policy, and audit together.

```typescript
import { AgentMeshClient } from '@agentmesh/sdk';
import { AgentMeshClient } from '@microsoft/agentmesh-sdk';

const client = AgentMeshClient.create('my-agent', {
policyRules: [{ action: 'data.*', effect: 'allow' }],
Expand All @@ -123,6 +129,125 @@ const result = await client.executeWithGovernance('data.read', { user: 'alice' }
// result: { decision, trustScore, auditEntry, executionTime }
```

### MCP Security

Use the MCP security primitives to govern both tool definitions and runtime traffic.
You can access the same governance surface either from the full SDK or from the standalone MCP package.

#### Full SDK install

```typescript
import {
ApprovalStatus,
CredentialRedactor,
MCPGateway,
MCPMessageSigner,
MCPResponseScanner,
MCPSecurityScanner,
MCPSessionAuthenticator,
MCPSlidingRateLimiter,
} from '@microsoft/agentmesh-sdk';
```

#### Standalone MCP governance install

```typescript
import {
ApprovalStatus,
CredentialRedactor,
MCPGateway,
MCPMessageSigner,
MCPResponseScanner,
MCPSecurityScanner,
MCPSessionAuthenticator,
MCPSlidingRateLimiter,
} from '@microsoft/agentmesh-mcp-governance';
```

Both entry points expose the same MCP governance primitives; the standalone package has zero dependency on the rest of the AGT SDK.

```typescript
import {
ApprovalStatus,
CredentialRedactor,
MCPGateway,
MCPMessageSigner,
MCPResponseScanner,
MCPSecurityScanner,
MCPSessionAuthenticator,
MCPSlidingRateLimiter,
} from '@microsoft/agentmesh-sdk';

const responseScanner = new MCPResponseScanner();
const redactor = new CredentialRedactor();
const sessionAuth = new MCPSessionAuthenticator({
secret: process.env.MCP_SESSION_SECRET!,
});
const messageSigner = new MCPMessageSigner({
secret: process.env.MCP_SIGNING_SECRET!,
});
const rateLimiter = new MCPSlidingRateLimiter({
maxRequests: 60,
windowMs: 60_000,
});
const securityScanner = new MCPSecurityScanner();

const gateway = new MCPGateway({
allowedTools: ['read_file', 'search_docs'],
sensitiveTools: ['deploy'],
rateLimiter,
approvalHandler: async ({ toolName }) =>
toolName === 'deploy'
? ApprovalStatus.Approved
: ApprovalStatus.Pending,
});

const toolDecision = await gateway.evaluateToolCall('agent-1', 'read_file', {
path: '/workspace/README.md',
});
const issuedSession = await sessionAuth.issueToken('agent-1');
const verifiedSession = await sessionAuth.verifyToken(
issuedSession.token,
'agent-1',
);
const signedMessage = messageSigner.sign({
tool: 'read_file',
args: { path: '/workspace/README.md' },
});
const verifiedMessage = await messageSigner.verify(signedMessage);
const toolThreats = securityScanner.scanTool(
'read_file',
'Read the contents of a file at the specified path.',
{
type: 'object',
properties: { path: { type: 'string' } },
required: ['path'],
additionalProperties: false,
},
'filesystem-server',
);
const scannedResponse = responseScanner.scan({
text: 'Search completed successfully.',
});
const redactedSecrets = redactor.redact({
bearerToken: 'Bearer abcdefghijklmnop',
});
```

The MCP surface adds:

- **MCPResponseScanner** — strips and flags prompt-injection tags, imperative phrasing, credential leaks, and exfiltration URLs before tool output reaches an LLM
- **MCPSessionAuthenticator** — HMAC-backed session tokens bound to agent identity with TTL expiry and concurrent-session enforcement
- **MCPMessageSigner** — HMAC-SHA256 request signing with timestamps and nonce replay protection
- **CredentialRedactor** — secret redaction for strings and nested object graphs
- **MCPSlidingRateLimiter** — per-agent sliding-window rate limiting
- **MCPSecurityScanner** — tool metadata scanning for poisoning, rug pulls, cross-server attacks, description injection, and schema abuse
- **MCPGateway** — deny-list, allow-list, sanitization, rate limiting, and approval orchestration

> [!NOTE]
> The built-in nonce and session stores are in-memory and intended for single-process development or tests.
> In multi-replica or enterprise deployments, implement the provided store interfaces against durable shared storage and inject shared clock/nonce providers for deterministic behavior.

## Development

```bash
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# MCP Express Server Example

This example shows a minimal Express.js server running the full AgentMesh MCP governance pipeline for a `POST /call-tool` endpoint.

## What it demonstrates

- `MCPGateway` allow-list, sanitization, rate limiting, and approval flow
- `MCPMessageSigner` signing and verification of tool calls
- `MCPSessionAuthenticator` session tokens with TTL-bound agent identity
- `MCPSlidingRateLimiter` per-agent request throttling
- `MCPSecurityScanner` request inspection for prompt-injection style content
- `MCPResponseScanner` output scanning for credentials and exfiltration patterns
- `CredentialRedactor` redaction before logging
- `GET /health` for readiness plus a short-lived demo session token

## Prerequisites

- Node 18+
- npm

## Install and run

```bash
cd packages/agent-mesh/sdks/typescript/examples/mcp-express-server
npm install
npx tsx src/server.ts
```

The example runs against the checked-out SDK source in this repository so reviewers can exercise the current branch without publishing a package first.

## Endpoints

- `GET /health` - readiness plus a demo session token for `demo-agent`
- `POST /call-tool` - signs, verifies, authenticates, rate-limits, scans, redacts, and executes a tool call

## Example curl flows

Fetch a demo session token:

```bash
curl http://127.0.0.1:3000/health
```

Use the returned `demoSessionToken` in a governed tool call:

```bash
curl -X POST http://127.0.0.1:3000/call-tool \
-H "content-type: application/json" \
-H "x-session-token: <PASTE_TOKEN_HERE>" \
-d '{
"agentId": "demo-agent",
"toolName": "search_docs",
"args": { "query": "OWASP MCP" }
}'
```

Trigger the path-traversal guard:

```bash
curl -X POST http://127.0.0.1:3000/call-tool \
-H "content-type: application/json" \
-H "x-session-token: <PASTE_TOKEN_HERE>" \
-d '{
"agentId": "demo-agent",
"toolName": "read_file",
"args": { "path": "../secrets.txt", "approved": true }
}'
```

Trigger response scanning for leaked credentials:

```bash
curl -X POST http://127.0.0.1:3000/call-tool \
-H "content-type: application/json" \
-H "x-session-token: <PASTE_TOKEN_HERE>" \
-d '{
"agentId": "demo-agent",
"toolName": "read_file",
"args": { "path": "workspace/secrets.txt", "approved": true }
}'
```

## OWASP MCP mapping

| Primitive | Example role |
| --- | --- |
| `MCPSessionAuthenticator` | Session binding and expiry |
| `MCPMessageSigner` | Signed tool-call envelopes |
| `MCPGateway` | Deny/allow/sanitize/approve pipeline |
| `MCPSlidingRateLimiter` | Request throttling |
| `MCPSecurityScanner` | Prompt-injection style request inspection |
| `MCPResponseScanner` | Output scanning and fail-closed blocking |
| `CredentialRedactor` | Safe audit logging |

## Run the smoke test

```bash
npm test
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "mcp-express-server-example",
"private": true,
"version": "0.0.1",
"description": "Public Preview — Express.js MCP governance example for the AgentMesh TypeScript SDK",
"type": "module",
"scripts": {
"start": "tsx src/server.ts",
"test": "tsx --test test/server.test.ts"
},
"peerDependencies": {
"@microsoft/agentmesh-sdk": "3.0.2"
},
"dependencies": {
"express": "4.21.2"
},
"devDependencies": {
"@types/express": "5.0.3",
"@types/node": "25.5.0",
"tsx": "4.19.3",
"typescript": "5.7.3"
},
"engines": {
"node": ">=18.0.0"
}
}
Loading
Loading