Skip to content
Open
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 apps/mesh/src/api/routes/decopilot/run-reactor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ function makeDeps(): RunReactorDeps {
addInflightAsyncJob: mock(() => Promise.resolve()),
findInflightAsyncJob: mock(() => Promise.resolve(null)),
removeInflightAsyncJob: mock(() => Promise.resolve()),
findLastUsedByVirtualMcpIds: mock(() => Promise.resolve(new Map())),
},
streamBuffer: { purge: mock(() => {}) } as unknown as StreamBuffer,
sseHub: { emit: mock(() => {}) },
Expand Down
1 change: 1 addition & 0 deletions apps/mesh/src/api/routes/decopilot/run-registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ function makeNoopDeps(): RunReactorDeps {
addInflightAsyncJob: mock(() => Promise.resolve()),
findInflightAsyncJob: mock(() => Promise.resolve(null)),
removeInflightAsyncJob: mock(() => Promise.resolve()),
findLastUsedByVirtualMcpIds: mock(() => Promise.resolve(new Map())),
},
streamBuffer: { purge: mock(() => {}) } as unknown as StreamBuffer,
sseHub: { emit: mock(() => {}) },
Expand Down
9 changes: 9 additions & 0 deletions apps/mesh/src/storage/ports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,15 @@ export interface ThreadStoragePort {
query: string,
): Promise<void>;

/**
* For each given virtual MCP id, return the timestamp and creator of the most recent thread.
* Used by the dedicated last-used endpoint; not on the agent fetch hot path.
*/
findLastUsedByVirtualMcpIds(
organizationId: string,
virtualMcpIds: string[],
): Promise<Map<string, { last_used_at: string; last_used_by: string }>>;

// Message operations - upserts by id (updates existing rows)
saveMessages(data: ThreadMessage[], organizationId: string): Promise<void>;
listMessages(
Expand Down
38 changes: 38 additions & 0 deletions apps/mesh/src/storage/threads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,15 @@ export class OrgScopedThreadStorage {
return this.inner.listByTriggerIds(this.requireOrg(), triggerIds, options);
}

findLastUsedByVirtualMcpIds(
virtualMcpIds: string[],
): Promise<Map<string, { last_used_at: string; last_used_by: string }>> {
return this.inner.findLastUsedByVirtualMcpIds(
this.requireOrg(),
virtualMcpIds,
);
}

addInflightAsyncJob(taskId: string, entry: InflightAsyncJob): Promise<void> {
return this.inner.addInflightAsyncJob(taskId, this.requireOrg(), entry);
}
Expand Down Expand Up @@ -508,6 +517,35 @@ export class SqlThreadStorage implements ThreadStoragePort {
};
}

async findLastUsedByVirtualMcpIds(
organizationId: string,
virtualMcpIds: string[],
): Promise<Map<string, { last_used_at: string; last_used_by: string }>> {
const result = new Map<
string,
{ last_used_at: string; last_used_by: string }
>();
if (virtualMcpIds.length === 0) return result;

const rows = await this.db
.selectFrom("threads")
.distinctOn("virtual_mcp_id")
.select(["virtual_mcp_id", "created_by", "created_at"])
.where("organization_id", "=", organizationId)
.where("virtual_mcp_id", "in", virtualMcpIds)
.orderBy("virtual_mcp_id")
.orderBy("created_at", "desc")
.execute();

for (const row of rows) {
result.set(row.virtual_mcp_id, {
last_used_at: toIsoString(row.created_at),
last_used_by: row.created_by,
});
}
return result;
}

/**
* Upserts thread messages by id.
* Inserts new messages; updates existing rows (by id) with parts, metadata, role, updated_at.
Expand Down
1 change: 1 addition & 0 deletions apps/mesh/src/tools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ const CORE_TOOLS = [
VirtualMCPTools.VIRTUAL_MCP_PLUGIN_CONFIG_GET,
VirtualMCPTools.VIRTUAL_MCP_PLUGIN_CONFIG_UPDATE,
VirtualMCPTools.VIRTUAL_MCP_PINNED_VIEWS_UPDATE,
VirtualMCPTools.VIRTUAL_MCP_LAST_USED_LIST,

// Ai providers tools
AiProvidersTools.AI_PROVIDERS_LIST,
Expand Down
7 changes: 7 additions & 0 deletions apps/mesh/src/tools/registry-metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ const ALL_TOOL_NAMES = [
"VIRTUAL_MCP_PLUGIN_CONFIG_GET",
"VIRTUAL_MCP_PLUGIN_CONFIG_UPDATE",
"VIRTUAL_MCP_PINNED_VIEWS_UPDATE",
"VIRTUAL_MCP_LAST_USED_LIST",

// Ai providers tools
"AI_PROVIDERS_LIST",
Expand Down Expand Up @@ -608,6 +609,11 @@ export const MANAGEMENT_TOOLS: ToolMetadata[] = [
description: "Update virtual MCP pinned sidebar views",
category: "Virtual MCPs",
},
{
name: "VIRTUAL_MCP_LAST_USED_LIST",
description: "Get last-used info for one or more virtual MCPs",
category: "Virtual MCPs",
},
{
name: "AI_PROVIDERS_LIST",
description: "List available AI providers",
Expand Down Expand Up @@ -924,6 +930,7 @@ const PERMISSION_CAPABILITIES: PermissionCapability[] = [
"COLLECTION_VIRTUAL_MCP_LIST",
"COLLECTION_VIRTUAL_MCP_GET",
"VIRTUAL_MCP_PLUGIN_CONFIG_GET",
"VIRTUAL_MCP_LAST_USED_LIST",
// View automations
"AUTOMATION_GET",
"AUTOMATION_LIST",
Expand Down
1 change: 1 addition & 0 deletions apps/mesh/src/tools/virtual/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export { COLLECTION_VIRTUAL_MCP_DELETE } from "./delete";
export { VIRTUAL_MCP_PLUGIN_CONFIG_GET } from "./plugin-config-get";
export { VIRTUAL_MCP_PLUGIN_CONFIG_UPDATE } from "./plugin-config-update";
export { VIRTUAL_MCP_PINNED_VIEWS_UPDATE } from "./pinned-views-update";
export { VIRTUAL_MCP_LAST_USED_LIST } from "./last-used-list";

// Re-export schema types (only types, not runtime schemas)
export type {
Expand Down
58 changes: 58 additions & 0 deletions apps/mesh/src/tools/virtual/last-used-list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* VIRTUAL_MCP_LAST_USED_LIST Tool
*
* Returns the most recent thread timestamp + creator per virtual MCP id.
* Kept on a dedicated endpoint so the agent fetch hot path doesn't pay for
* this query on every request.
*/

import { z } from "zod";
import { defineTool } from "../../core/define-tool";
import { requireAuth, requireOrganization } from "../../core/mesh-context";

const InputSchema = z.object({
ids: z.array(z.string()).describe("Virtual MCP ids to look up"),
});

const OutputSchema = z.object({
items: z.array(
z.object({
id: z.string(),
last_used_at: z.string().optional(),
last_used_by: z.string().optional(),
}),
),
});

export const VIRTUAL_MCP_LAST_USED_LIST = defineTool({
name: "VIRTUAL_MCP_LAST_USED_LIST",
description:
"Get last-used info (timestamp + user) for one or more virtual MCPs, derived from the most recent thread per agent.",
annotations: {
title: "List Virtual MCP Last Used",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
inputSchema: InputSchema,
outputSchema: OutputSchema,

handler: async (input, ctx) => {
requireAuth(ctx);
requireOrganization(ctx);
await ctx.access.check();

const map = await ctx.storage.threads.findLastUsedByVirtualMcpIds(
input.ids,
);

return {
items: input.ids.map((id) => ({
id,
last_used_at: map.get(id)?.last_used_at,
last_used_by: map.get(id)?.last_used_by,
})),
};
},
});
13 changes: 9 additions & 4 deletions apps/mesh/src/web/components/project-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,15 @@ import {

interface ProjectCardProps {
project: VirtualMCPEntity;
lastUsedAt?: string;
onDeleteClick?: (e: React.MouseEvent) => void;
}

export function ProjectCard({ project, onDeleteClick }: ProjectCardProps) {
export function ProjectCard({
project,
lastUsedAt,
onDeleteClick,
}: ProjectCardProps) {
const navigateToAgent = useNavigateToAgent();

return (
Expand Down Expand Up @@ -91,9 +96,9 @@ export function ProjectCard({ project, onDeleteClick }: ProjectCardProps) {
<div className="border-t border-border mt-auto">
<div className="h-10 flex items-center px-4.5">
<p className="text-xs text-muted-foreground">
{formatDistanceToNow(new Date(project.updated_at), {
addSuffix: true,
})}
{lastUsedAt
? `Last used ${formatDistanceToNow(new Date(lastUsedAt), { addSuffix: true })}`
: `Updated ${formatDistanceToNow(new Date(project.updated_at), { addSuffix: true })}`}
</p>
</div>
</div>
Expand Down
6 changes: 6 additions & 0 deletions apps/mesh/src/web/routes/agents-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
useProjectContext,
useVirtualMCPActions,
useVirtualMCPs,
useVirtualMCPsLastUsed,
} from "@decocms/mesh-sdk";
import { Page } from "@/web/components/page";
import { ProjectCard } from "@/web/components/project-card";
Expand Down Expand Up @@ -68,6 +69,10 @@ export default function AgentsListPage() {
s.description?.toLowerCase().includes(lowerSearch)),
);

const { data: lastUsedMap } = useVirtualMCPsLastUsed(
filteredAgents.map((a) => a.id),
);

// Check if studio pack is already installed
const studioPackInstalled = agents.some((a) => isStudioPackAgent(a.id));

Expand Down Expand Up @@ -245,6 +250,7 @@ export default function AgentsListPage() {
<ProjectCard
key={agent.id}
project={agent}
lastUsedAt={lastUsedMap?.get(agent.id)?.last_used_at}
onDeleteClick={() =>
setDeleteTarget({
id: agent.id,
Expand Down
17 changes: 14 additions & 3 deletions apps/mesh/src/web/views/virtual-mcp/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { formatDistanceToNow } from "date-fns";
import { generatePrefixedId } from "@/shared/utils/generate-id";
import type { VirtualMCPEntity } from "@/tools/virtual/schema";
import { getUIResourceUri } from "@/mcp-apps/types.ts";
Expand Down Expand Up @@ -64,6 +65,7 @@ import {
useProjectContext,
useVirtualMCP,
useVirtualMCPActions,
useVirtualMCPsLastUsed,
} from "@decocms/mesh-sdk";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQuery, useQueryClient } from "@tanstack/react-query";
Expand Down Expand Up @@ -997,6 +999,8 @@ function VirtualMcpDetailViewWithData({
}) {
const { org } = useProjectContext();
const actions = useVirtualMCPActions();
const { data: lastUsedMap } = useVirtualMCPsLastUsed([virtualMcp.id]);
const lastUsedAt = lastUsedMap?.get(virtualMcp.id)?.last_used_at;
const connectionActions = useConnectionActions();
const queryClient = useQueryClient();
const client = useMCPClient({
Expand Down Expand Up @@ -1548,20 +1552,27 @@ Define step-by-step how the agent should handle requests.
</div>

{/* Creator metadata */}
<div className="flex items-center gap-2 -mt-6 text-muted-foreground">
<div className="flex items-center gap-2 -mt-6 text-sm text-muted-foreground">
<User
id={virtualMcp.created_by}
size="2xs"
className="text-sm text-muted-foreground"
/>
<span className="text-muted-foreground/50 text-sm">·</span>
<span className="text-sm">
<span className="text-muted-foreground/50">·</span>
<span>
Created{" "}
{new Date(virtualMcp.created_at).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
})}
</span>
<span className="text-muted-foreground/50">·</span>
<span>
{lastUsedAt
? `Last used ${formatDistanceToNow(new Date(lastUsedAt), { addSuffix: true })}`
: "Never used"}
</span>
</div>

{/* Connections section */}
Expand Down
2 changes: 2 additions & 0 deletions packages/mesh-sdk/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ export {
useVirtualMCPs,
useVirtualMCP,
useVirtualMCPActions,
useVirtualMCPsLastUsed,
type VirtualMCPFilter,
type UseVirtualMCPsOptions,
type VirtualMCPLastUsed,
} from "./use-virtual-mcp";
41 changes: 41 additions & 0 deletions packages/mesh-sdk/src/hooks/use-virtual-mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* These hooks offer a reactive interface for accessing and manipulating virtual MCPs.
*/

import { useQuery } from "@tanstack/react-query";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import type { VirtualMCPEntity } from "../types/virtual-mcp";
import { useProjectContext } from "../context";
import {
Expand All @@ -17,6 +19,12 @@ import {
import { useMCPClient } from "./use-mcp-client";
import { SELF_MCP_ALIAS_ID } from "../lib/constants";

export interface VirtualMCPLastUsed {
id: string;
last_used_at?: string;
last_used_by?: string;
}

/**
* Filter definition for virtual MCPs (matches @deco/ui Filter shape)
*/
Expand Down Expand Up @@ -77,6 +85,39 @@ export function useVirtualMCP(
return dbVirtualMCP;
}

/**
* Hook to fetch last-used info (most recent thread timestamp + user) for a set
* of virtual MCPs. Backed by VIRTUAL_MCP_LAST_USED_LIST so the data isn't
* loaded on the agent fetch hot path.
*/
export function useVirtualMCPsLastUsed(ids: string[]) {
const { org } = useProjectContext();
const client = useMCPClient({
connectionId: SELF_MCP_ALIAS_ID,
orgId: org.id,
orgSlug: org.slug,
});
const sortedIds = [...ids].sort();

return useQuery<Map<string, VirtualMCPLastUsed>>({
queryKey: ["virtual-mcp", "last-used", org.id, sortedIds],
enabled: sortedIds.length > 0,
staleTime: 30_000,
queryFn: async () => {
const result = (await client.callTool({
name: "VIRTUAL_MCP_LAST_USED_LIST",
arguments: { ids: sortedIds },
})) as CallToolResult;
const payload = (result.structuredContent ?? { items: [] }) as {
items: VirtualMCPLastUsed[];
};
const map = new Map<string, VirtualMCPLastUsed>();
for (const item of payload.items) map.set(item.id, item);
return map;
},
});
}

/**
* Hook to get virtual MCP mutation actions (create, update, delete)
*
Expand Down
2 changes: 2 additions & 0 deletions packages/mesh-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,10 @@ export {
useVirtualMCPs,
useVirtualMCP,
useVirtualMCPActions,
useVirtualMCPsLastUsed,
type VirtualMCPFilter,
type UseVirtualMCPsOptions,
type VirtualMCPLastUsed,
} from "./hooks";

// Types
Expand Down
Loading