Skip to content

Workers Observability migrate responses to TSV's #140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 2, 2025
Merged
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/workers-observability/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
},
"dependencies": {
"@cloudflare/workers-oauth-provider": "0.0.5",
"@fast-csv/format": "5.0.2",
"@hono/zod-validator": "0.4.3",
"@modelcontextprotocol/sdk": "1.10.2",
"@repo/mcp-common": "workspace:*",
Expand Down
109 changes: 107 additions & 2 deletions apps/workers-observability/src/tools/observability.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { writeToString } from '@fast-csv/format'

import {
handleWorkerLogsKeys,
handleWorkerLogsValues,
Expand Down Expand Up @@ -60,6 +62,100 @@ This tool provides three primary views of your Worker data:
}
try {
const response = await queryWorkersObservability(agent.props.accessToken, accountId, query)

if (query.view === 'calculations') {
let data = ''
for (const calculation of response?.calculations || []) {
const alias = calculation.alias || calculation.calculation
const aggregates = calculation.aggregates.map((agg) => {
const keys = agg.groups?.reduce(
(acc, group) => {
acc[`${group.key}`] = `${group.value}`
return acc
},
{} as Record<string, string>
)
return {
...keys,
[alias]: agg.value,
}
})

const aggregatesString = await writeToString(aggregates, {
headers: true,
delimiter: '\t',
})

const series = calculation.series.map(({ time, data }) => {
return {
time,
...data.reduce(
(acc, point) => {
const key = point.groups?.reduce((acc, group) => {
return `${acc} * ${group.value}`
}, '')
if (!key) {
return {
...acc,
[alias]: point.value,
}
}
return {
...acc,
key,
[alias]: point.value,
}
},
{} as Record<string, string | number | undefined>
),
}
})
const seriesString = await writeToString(series, { headers: true, delimiter: '\t' })
data = data + '\n' + `## ${alias}`
data = data + '\n' + `### Aggregation`
data = data + '\n' + aggregatesString
data = data + '\n' + `### Series`
data = data + '\n' + seriesString
}

return {
content: [
{
type: 'text',
text: data,
},
],
}
}

if (query.view === 'events') {
const events = response?.events?.events
return {
content: [
{
type: 'text',
text: JSON.stringify(events),
},
],
}
}

if (query.view === 'invocations') {
const invocations = Object.entries(response?.invocations || {}).map(([_, logs]) => {
const invocationLog = logs.find((log) => log.$metadata.type === 'cf-worker-event')
return invocationLog?.$metadata ?? logs[0]?.$metadata
})

const tsv = await writeToString(invocations, { headers: true, delimiter: '\t' })
return {
content: [
{
type: 'text',
text: tsv,
},
],
}
}
return {
content: [
{
Expand Down Expand Up @@ -110,11 +206,16 @@ This tool provides three primary views of your Worker data:
}
try {
const result = await handleWorkerLogsKeys(agent.props.accessToken, accountId, keysQuery)

const tsv = await writeToString(
result.map((key) => ({ type: key.type, key: key.key })),
{ headers: true, delimiter: '\t' }
)
return {
content: [
{
type: 'text',
text: JSON.stringify(result),
text: tsv,
},
],
}
Expand Down Expand Up @@ -155,11 +256,15 @@ This tool provides three primary views of your Worker data:
}
try {
const result = await handleWorkerLogsValues(agent.props.accessToken, accountId, valuesQuery)
const tsv = await writeToString(
result?.map((value) => ({ type: value.type, value: value.value })) || [],
{ headers: true, delimiter: '\t' }
)
return {
content: [
{
type: 'text',
text: JSON.stringify(result),
text: tsv,
},
],
}
Expand Down
5 changes: 5 additions & 0 deletions packages/mcp-common/src/api/workers-observability.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { env } from 'cloudflare:workers'

import { fetchCloudflareApi } from '../cloudflare-api'
import {
zKeysResponse,
Expand All @@ -23,6 +25,8 @@ export async function queryWorkersObservability(
accountId: string,
query: QueryRunRequest
): Promise<z.infer<typeof zReturnedQueryRunResult> | null> {
// @ts-expect-error We don't have actual env in this package
const environment = env.ENVIRONMENT
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could probably also pass through this env in the params so we don't need to expect error here.

Kinda like what do here https://github.com/cloudflare/mcp-server-cloudflare/blob/main/packages/mcp-common/src/dev-mode.ts#L6

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will fix in a follow up on monday :)

const data = await fetchCloudflareApi({
endpoint: '/workers/observability/telemetry/query',
accountId,
Expand All @@ -32,6 +36,7 @@ export async function queryWorkersObservability(
method: 'POST',
headers: {
'Content-Type': 'application/json',
'workers-observability-origin': `workers-observability-mcp-${environment}`,
Copy link
Member

@Maximo-Guk Maximo-Guk May 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can come up with a general header name, which every mcp server uses?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is specific to our backend, happy to add a general one too

Copy link
Member

@Maximo-Guk Maximo-Guk May 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome, maybe we can set our user agent to the server name / version ( the ones pulled from package.json )

Also doesn't have to be in this PR!

},
body: JSON.stringify({ ...query, timeframe: fixTimeframe(query.timeframe) }),
},
Expand Down
10 changes: 10 additions & 0 deletions packages/mcp-common/src/cloudflare-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ export async function fetchCloudflareApi<T>({
}): Promise<T> {
const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}${endpoint}`

// @ts-expect-error We don't have actual env in this package
if (env.DEV_DISABLE_OAUTH) {
options.headers = {
...options.headers,
// @ts-expect-error We don't have actual env in this package
'X-Auth-Email': env.DEV_CLOUDFLARE_EMAIL,
// @ts-expect-error We don't have actual env in this package
'X-Auth-Key': env.DEV_CLOUDFLARE_API_TOKEN,
}
}
const response = await fetch(url, {
...options,
headers: {
Expand Down
40 changes: 40 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading