From 36cab1d21f3dc2aab35fc1388fa086641c5060ac Mon Sep 17 00:00:00 2001 From: alkalinan Date: Tue, 24 Nov 2026 12:40:55 +0100 Subject: [PATCH 01/11] Add the MCP-OpenTelemetry-UI package with an empty Call graph inspector tab --- src/BaselineOfMCP/BaselineOfMCP.class.st | 4 ++- src/MCP-OpenTelemetry-UI/MCP.extension.st | 8 ++++++ .../MCPCallGraphPresenter.class.st | 28 +++++++++++++++++++ .../ManifestMCPOpenTelemetryUI.class.st | 16 +++++++++++ src/MCP-OpenTelemetry-UI/package.st | 1 + 5 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 src/MCP-OpenTelemetry-UI/MCP.extension.st create mode 100644 src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st create mode 100644 src/MCP-OpenTelemetry-UI/ManifestMCPOpenTelemetryUI.class.st create mode 100644 src/MCP-OpenTelemetry-UI/package.st diff --git a/src/BaselineOfMCP/BaselineOfMCP.class.st b/src/BaselineOfMCP/BaselineOfMCP.class.st index a047d39b..be736a8b 100644 --- a/src/BaselineOfMCP/BaselineOfMCP.class.st +++ b/src/BaselineOfMCP/BaselineOfMCP.class.st @@ -87,11 +87,12 @@ BaselineOfMCP >> defineGroups: spec [ group: 'IDE' with: #( 'MCP-IDE' ); group: 'UI' with: #( 'MCP-UI' ); group: 'Telemetry' with: #( 'MCP-OpenTelemetry' ); + group: 'Telemetry UI' with: #( 'MCP-OpenTelemetry-UI' ); group: 'Tests' with: #( 'MCP-Tests' ); group: 'UI Tests' with: #( 'MCP-UI-Tests' ); group: 'Telemetry Tests' with: #( 'MCP-OpenTelemetry-Tests' ); group: 'default' with: #( 'Core' 'IDE' 'UI' ); - group: 'all' with: #( 'default' 'Telemetry' 'Tests' 'UI Tests' 'Telemetry Tests' ) + group: 'all' with: #( 'default' 'Telemetry' 'Telemetry UI' 'Tests' 'UI Tests' 'Telemetry Tests' ) ] { #category : 'baselines' } @@ -102,6 +103,7 @@ BaselineOfMCP >> definePackages: spec [ spec package: 'MCP-IDE' with: [ spec requires: #( 'Core' 'PCRE2' ) ]. spec package: 'MCP-UI' with: [ spec requires: #( 'Core' ) ]. spec package: 'MCP-OpenTelemetry' with: [ spec requires: #( 'Core' 'OpenTelemetry' ) ]. + spec package: 'MCP-OpenTelemetry-UI' with: [ spec requires: #( 'UI' 'Telemetry' ) ]. spec package: 'MCP-OpenTelemetry-Tests' with: [ spec requires: #( 'MCP-OpenTelemetry' 'IDE' 'MCP-Tests-Resources' ) ]. spec package: 'MCP-Tests-Resources' with: [ spec requires: #( 'IDE' ) ]. spec package: 'MCP-Tests-RunResources' with: [ spec requires: #( 'MCP-Tests-Resources' ) ]. diff --git a/src/MCP-OpenTelemetry-UI/MCP.extension.st b/src/MCP-OpenTelemetry-UI/MCP.extension.st new file mode 100644 index 00000000..05517748 --- /dev/null +++ b/src/MCP-OpenTelemetry-UI/MCP.extension.st @@ -0,0 +1,8 @@ +Extension { #name : 'MCP' } + +{ #category : '*MCP-OpenTelemetry-UI' } +MCP >> inspectionCallGraph: aBuilder [ + + + ^ MCPCallGraphPresenter on: self +] diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st new file mode 100644 index 00000000..2c84672d --- /dev/null +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st @@ -0,0 +1,28 @@ +" +Spec presenter for the call graph of an MCP server: the successive calls its OpenTelemetry spans record, as an object-centric process model whose central object is the tool. It is the third inspector tab of a server, beside its dashboard and its observability, and is only there once MCP-OpenTelemetry is loaded. +" +Class { + #name : 'MCPCallGraphPresenter', + #superclass : 'SpPresenterWithModel', + #instVars : [ + 'statusLabel' + ], + #category : 'MCP-OpenTelemetry-UI', + #package : 'MCP-OpenTelemetry-UI' +} + +{ #category : 'layout' } +MCPCallGraphPresenter >> defaultLayout [ + + ^ SpBoxLayout newTopToBottom + borderWidth: 8; + add: statusLabel expand: false; + yourself +] + +{ #category : 'initialization' } +MCPCallGraphPresenter >> initializePresenters [ + + statusLabel := self newLabel. + statusLabel label: 'Call graph: nothing to show yet.' +] diff --git a/src/MCP-OpenTelemetry-UI/ManifestMCPOpenTelemetryUI.class.st b/src/MCP-OpenTelemetry-UI/ManifestMCPOpenTelemetryUI.class.st new file mode 100644 index 00000000..c7403001 --- /dev/null +++ b/src/MCP-OpenTelemetry-UI/ManifestMCPOpenTelemetryUI.class.st @@ -0,0 +1,16 @@ +" +What the inspector shows of an MCP server beyond MCP-UI once OpenTelemetry is loaded: the call graph its spans build. It is a package of its own so that MCP-UI does not depend on OpenTelemetry, nor MCP-OpenTelemetry on Spec; the baseline loads it with the 'Telemetry UI' group. +" +Class { + #name : 'ManifestMCPOpenTelemetryUI', + #superclass : 'PackageManifest', + #category : 'MCP-OpenTelemetry-UI-Manifest', + #package : 'MCP-OpenTelemetry-UI', + #tag : 'Manifest' +} + +{ #category : 'formatting' } +ManifestMCPOpenTelemetryUI class >> formatter [ + + ^ ManifestBaselineOfMCP formatter +] diff --git a/src/MCP-OpenTelemetry-UI/package.st b/src/MCP-OpenTelemetry-UI/package.st new file mode 100644 index 00000000..3939eaaf --- /dev/null +++ b/src/MCP-OpenTelemetry-UI/package.st @@ -0,0 +1 @@ +Package { #name : 'MCP-OpenTelemetry-UI' } From 9b7be4007263a10de777cbaa8e628d834cb1c70c Mon Sep 17 00:00:00 2001 From: alkalinan Date: Tue, 24 Nov 2026 12:46:51 +0100 Subject: [PATCH 02/11] Keep spans in memory for the image when local spans are on, without exporting --- ...TelemetryObservabilityBackendTest.class.st | 48 ++++++++++++ ...MCPOpenTelemetryLocalSpanExporter.class.st | 35 +++++++++ .../MCPOpenTelemetryLocalSpanStore.class.st | 64 ++++++++++++++++ ...OpenTelemetryObservabilityBackend.class.st | 74 ++++++++++++++++--- 4 files changed, 211 insertions(+), 10 deletions(-) create mode 100644 src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanExporter.class.st create mode 100644 src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanStore.class.st diff --git a/src/MCP-OpenTelemetry-Tests/MCPOpenTelemetryObservabilityBackendTest.class.st b/src/MCP-OpenTelemetry-Tests/MCPOpenTelemetryObservabilityBackendTest.class.st index 5cf6c4e4..dca52cfe 100644 --- a/src/MCP-OpenTelemetry-Tests/MCPOpenTelemetryObservabilityBackendTest.class.st +++ b/src/MCP-OpenTelemetry-Tests/MCPOpenTelemetryObservabilityBackendTest.class.st @@ -1147,6 +1147,17 @@ MCPOpenTelemetryObservabilityBackendTest >> testSessionLifecycleGoesThroughTheLo self assert: exporter snapshots isEmpty description: 'Session events are logs, not spans.' ] +{ #category : 'tests' } +MCPOpenTelemetryObservabilityBackendTest >> testSettingsThatAskForNoTracesMakeNoSpansWhenTheImageDoesNotKeepThem [ + + | mcp | + MCPOpenTelemetryObservabilityBackend localSpanStore clear. + mcp := MCP new. + backend := mcp useOpenTelemetryObservabilityWith: (self settingsAskingForTraces: false). + backend recordToolCallFinish: self startToolCall result: self successToolResult error: nil. + self assert: MCPOpenTelemetryObservabilityBackend localSpanStore size equals: 0 +] + { #category : 'tests' } MCPOpenTelemetryObservabilityBackendTest >> testSettingsThatAskForNoTracesRecordOnlyLocally [ @@ -1161,6 +1172,27 @@ MCPOpenTelemetryObservabilityBackendTest >> testSettingsThatAskForNoTracesRecord self assert: (backend recentCalls collect: [ :each | each toolName ]) asArray equals: #( #method_compile ) ] +{ #category : 'tests' } +MCPOpenTelemetryObservabilityBackendTest >> testSettingsThatAskForNoTracesStillMakeSpansWhenTheImageKeepsThem [ + + | mcp store flag | + store := MCPOpenTelemetryObservabilityBackend localSpanStore. + store clear. + flag := MCPOpenTelemetryObservabilityBackend classVariableNamed: #LocalSpansEnabled. + [ + flag value: true. + mcp := MCP new. + backend := mcp useOpenTelemetryObservabilityWith: (self settingsAskingForTraces: false). + self assert: backend isRecordingTraces. + self assert: (OTMeterProvider current instVarNamed: 'metricReaders') isEmpty. + self assert: OTLoggerProvider current logRecordProcessors isEmpty. + backend recordToolCallFinish: self startToolCall result: self successToolResult error: nil. + self assert: store size equals: 1. + self assert: store snapshots first name equals: 'tools/call method_compile' ] ensure: [ + flag value: false. + store clear ] +] + { #category : 'tests' } MCPOpenTelemetryObservabilityBackendTest >> testStartingTheImageAgainConfiguresItsBackendsFromTheSettingsItNowHas [ @@ -1267,6 +1299,22 @@ MCPOpenTelemetryObservabilityBackendTest >> testTheExceptionAnErrorAnswerNamesIs self assert: (self attributeNamed: 'pharo.mcp.error.kind' in: snapshot) equals: 'domain' ] +{ #category : 'tests' } +MCPOpenTelemetryObservabilityBackendTest >> testTheLocalSpanStoreKeepsTheMostRecentSpansAndItsExporterStopsOnceShutDown [ + + | store localExporter | + store := MCPOpenTelemetryLocalSpanStore new + maxSpans: 3; + yourself. + localExporter := MCPOpenTelemetryLocalSpanExporter on: store. + self assert: (localExporter export: #( 1 2 )). + self assert: (localExporter export: #( 3 4 )). + self assert: store snapshots equals: #( 2 3 4 ). + localExporter shutdown. + self deny: (localExporter export: #( 5 )). + self assert: store snapshots equals: #( 2 3 4 ) +] + { #category : 'tests' } MCPOpenTelemetryObservabilityBackendTest >> testTheOptionsACallChoseAreReported [ "As the evaluation counts them: an optional property given, an enumerated value other than the default, and the list form of a property that also takes one value." diff --git a/src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanExporter.class.st b/src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanExporter.class.st new file mode 100644 index 00000000..bfd14f47 --- /dev/null +++ b/src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanExporter.class.st @@ -0,0 +1,35 @@ +" +A span exporter that hands every snapshot to a MCPOpenTelemetryLocalSpanStore and sends nothing. It follows OTNoopSpanExporter: the export respects the exporter lock and stops once the exporter is shut down. +" +Class { + #name : 'MCPOpenTelemetryLocalSpanExporter', + #superclass : 'OTSpanExporter', + #instVars : [ + 'store' + ], + #category : 'MCP-OpenTelemetry', + #package : 'MCP-OpenTelemetry' +} + +{ #category : 'instance creation' } +MCPOpenTelemetryLocalSpanExporter class >> on: aSpanStore [ + + ^ self new + store: aSpanStore; + yourself +] + +{ #category : 'exporting' } +MCPOpenTelemetryLocalSpanExporter >> export: spanSnapshots [ + + ^ self withExportLockDo: [ + self isShutdown ifTrue: [ ^ false ]. + store addAll: spanSnapshots. + true ] +] + +{ #category : 'accessing' } +MCPOpenTelemetryLocalSpanExporter >> store: aSpanStore [ + + store := aSpanStore +] diff --git a/src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanStore.class.st b/src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanStore.class.st new file mode 100644 index 00000000..cbd00494 --- /dev/null +++ b/src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanStore.class.st @@ -0,0 +1,64 @@ +" +The spans the image keeps in memory for itself, to be read back by what inspects it, such as the call graph of the inspector, whether or not any are exported. It holds the most recent maxSpans snapshots, oldest dropped first. It outlives the providers: a reconfiguration shuts down the exporter that fed it and makes another, which feeds the same store. +" +Class { + #name : 'MCPOpenTelemetryLocalSpanStore', + #superclass : 'Object', + #instVars : [ + 'snapshots', + 'mutex', + 'maxSpans' + ], + #category : 'MCP-OpenTelemetry', + #package : 'MCP-OpenTelemetry' +} + +{ #category : 'adding' } +MCPOpenTelemetryLocalSpanStore >> addAll: spanSnapshots [ + + mutex critical: [ + snapshots addAll: spanSnapshots. + [ snapshots size > maxSpans ] whileTrue: [ snapshots removeFirst ] ] +] + +{ #category : 'removing' } +MCPOpenTelemetryLocalSpanStore >> clear [ + + mutex critical: [ snapshots removeAll ] +] + +{ #category : 'initialization' } +MCPOpenTelemetryLocalSpanStore >> initialize [ + + super initialize. + snapshots := OrderedCollection new. + mutex := Mutex new. + maxSpans := 5000 +] + +{ #category : 'accessing' } +MCPOpenTelemetryLocalSpanStore >> maxSpans [ + + ^ maxSpans +] + +{ #category : 'accessing' } +MCPOpenTelemetryLocalSpanStore >> maxSpans: anInteger [ + + mutex critical: [ + maxSpans := anInteger. + [ snapshots size > maxSpans ] whileTrue: [ snapshots removeFirst ] ] +] + +{ #category : 'accessing' } +MCPOpenTelemetryLocalSpanStore >> size [ + + ^ mutex critical: [ snapshots size ] +] + +{ #category : 'accessing' } +MCPOpenTelemetryLocalSpanStore >> snapshots [ + "The spans kept, oldest first, as a copy that later exports do not change." + + ^ mutex critical: [ snapshots asArray ] +] diff --git a/src/MCP-OpenTelemetry/MCPOpenTelemetryObservabilityBackend.class.st b/src/MCP-OpenTelemetry/MCPOpenTelemetryObservabilityBackend.class.st index d802d8ad..124a3f42 100644 --- a/src/MCP-OpenTelemetry/MCPOpenTelemetryObservabilityBackend.class.st +++ b/src/MCP-OpenTelemetry/MCPOpenTelemetryObservabilityBackend.class.st @@ -26,6 +26,8 @@ Class { ], #classVars : [ 'Backends', + 'LocalSpanStore', + 'LocalSpansEnabled', 'OwnPackageNames', 'PharoPackageNames', 'ProviderSettings', @@ -37,6 +39,25 @@ Class { #package : 'MCP-OpenTelemetry' } +{ #category : 'configuring' } +MCPOpenTelemetryObservabilityBackend class >> attachLocalSpansExporting: exporting [ + "Feeds localSpanStore from the providers just made, when the image keeps its spans. Beside the exporters the settings chose when they ask for traces; else the providers are the image's own: a tracer provider that only feeds the store, and meter and logger providers with nothing to send to, so that the defaults the SDK would make, which export to a collector, never exist." + + | processor | + self isLocalSpansEnabled ifFalse: [ ^ self ]. + processor := OTSimpleSpanProcessor new + exporter: (MCPOpenTelemetryLocalSpanExporter on: self localSpanStore); + yourself. + exporting + ifTrue: [ OTTracerProvider current addSpanProcessor: processor ] + ifFalse: [ + OTTracerProvider current: (OTTracerProvider new + spanProcessor: processor; + yourself). + OTMeterProvider current: OTMeterProvider new. + OTLoggerProvider current: OTLoggerProvider new ] +] + { #category : 'reporting' } MCPOpenTelemetryObservabilityBackend class >> baselineClassNameOf: aProjectSpec [ "The class of the baseline a project specification names: the one it says, since a project's name need not be its baseline's, or else the one its name gives by convention." @@ -103,6 +124,20 @@ MCPOpenTelemetryObservabilityBackend class >> initialize [ SessionManager default registerToolClassNamed: self name ] +{ #category : 'local spans' } +MCPOpenTelemetryObservabilityBackend class >> isLocalSpansEnabled [ + "Whether the image keeps its spans in memory, in localSpanStore, whatever the settings say about exporting them. Off until someone turns it on, and it stays as the image was saved." + + ^ LocalSpansEnabled == true +] + +{ #category : 'local spans' } +MCPOpenTelemetryObservabilityBackend class >> localSpanStore [ + "Where the image keeps its spans for itself, whether or not they are exported." + + ^ LocalSpanStore ifNil: [ LocalSpanStore := MCPOpenTelemetryLocalSpanStore new ] +] + { #category : 'reporting' } MCPOpenTelemetryObservabilityBackend class >> ownPackageNames [ "The packages MCP's baseline lists, read once per image session. None when MCP was loaded without its baseline, so that nothing is taken for MCP's own by mistake." @@ -190,15 +225,17 @@ MCPOpenTelemetryObservabilityBackend class >> providersMutex [ { #category : 'configuring' } MCPOpenTelemetryObservabilityBackend class >> reconfigure: someBackends with: aSettings [ - "Configures each of someBackends afresh from aSettings, the providers once for all of them. The providers are global and may be the user's: they are rebuilt only when the settings ask for traces or one of these backends was configured to record through them, and then only when the settings in effect are not those they were made from, so that configuring another server leaves the calls running recording as they started. A call starting its span meanwhile waits for all of it, so that it starts in the providers before or after, never in those being replaced." + "Configures each of someBackends afresh from aSettings, the providers once for all of them. The providers are global and may be the user's: they are rebuilt only when the settings ask for traces, or the image keeps its spans, or one of these backends was configured to record through them, and then only when the settings in effect are not those they were made from, so that configuring another server leaves the calls running recording as they started. A call starting its span meanwhile waits for all of it, so that it starts in the providers before or after, never in those being replaced." self providersMutex critical: [ - | wanted settings | - wanted := self wantsTraces: aSettings. + | exporting wanted settings | + exporting := self settingsAskForTraces: aSettings. + wanted := exporting or: [ self isLocalSpansEnabled ]. settings := self settingsInEffectOf: aSettings. ((wanted or: [ someBackends anySatisfy: [ :each | each isConfiguredForTraces ] ]) and: [ ProviderSettings ~= settings ]) ifTrue: [ self resetProviders. + self attachLocalSpansExporting: exporting. ProviderSettings := settings ]. someBackends do: [ :each | [ each configureFor: each serverInfo configured: wanted ] @@ -293,6 +330,17 @@ MCPOpenTelemetryObservabilityBackend class >> retiredTracerProviders [ ^ RetiredTracerProviders ifNil: [ RetiredTracerProviders := OrderedCollection new ] ] +{ #category : 'configuring' } +MCPOpenTelemetryObservabilityBackend class >> settingsAskForTraces: aSettings [ + "Whether aSettings ask for traces to be exported, once MCP's settings file, when it gives any, has replaced the environment's." + + ^ [ + aSettings apply. + aSettings isConfigured ] + on: Error + do: [ false ] +] + { #category : 'configuring' } MCPOpenTelemetryObservabilityBackend class >> settingsInEffectOf: aSettings [ "The settings the providers would be made from now, or a value equal to no other when they cannot be read." @@ -341,13 +389,14 @@ MCPOpenTelemetryObservabilityBackend class >> spansInFlight [ { #category : 'system startup' } MCPOpenTelemetryObservabilityBackend class >> startUp: resuming [ - "An image starting again may run elsewhere, with other settings or none: every backend of this kind is configured afresh from them, before its server answers a call, and its providers are made again, whatever settings the last session made them from. The calls the last session was running when it saved the image go on in this one, and record nothing when they end; the providers kept for them are shut down. An image without a backend of this kind leaves OpenTelemetry alone." + "An image starting again may run elsewhere, with other settings or none: every backend of this kind is configured afresh from them, before its server answers a call, and its providers are made again, whatever settings the last session made them from. The calls the last session was running when it saved the image go on in this one, and record nothing when they end; the providers kept for them are shut down. The spans the last session kept for the image belong to it and are dropped. An image without a backend of this kind leaves OpenTelemetry alone." | backends retired | resuming ifFalse: [ ^ self ]. OwnPackageNames := nil. PharoPackageNames := nil. ProviderSettings := nil. + LocalSpanStore ifNotNil: [ :store | store clear ]. retired := self providersMutex critical: [ | providers | providers := self retiredTracerProviders collect: [ :each | each key ]. @@ -362,15 +411,20 @@ MCPOpenTelemetryObservabilityBackend class >> startUp: resuming [ do: [ :error | error return: nil ] ] +{ #category : 'local spans' } +MCPOpenTelemetryObservabilityBackend class >> useLocalSpans: aBoolean [ + "Turns the keeping of spans in memory on or off, and makes the providers again, for every backend of this kind the image holds. With settings that ask for no traces nothing is exported: the spans are made for the image alone." + + LocalSpansEnabled := aBoolean == true. + self providersMutex critical: [ ProviderSettings := nil ]. + self reconfigure: self registeredBackends asArray with: MCPOpenTelemetrySettings current +] + { #category : 'configuring' } MCPOpenTelemetryObservabilityBackend class >> wantsTraces: aSettings [ - "Whether aSettings ask for traces, once MCP's settings file, when it gives any, has replaced the environment's." + "Whether spans are to be made: aSettings ask for traces, or the image keeps its spans for itself." - ^ [ - aSettings apply. - aSettings isConfigured ] - on: Error - do: [ false ] + ^ (self settingsAskForTraces: aSettings) or: [ self isLocalSpansEnabled ] ] { #category : 'private - recording' } From 001c7870f5afe62182ad2b46e3369ba01471a686 Mon Sep 17 00:00:00 2001 From: alkalinan Date: Tue, 24 Nov 2026 12:52:40 +0100 Subject: [PATCH 03/11] Add a switch for local spans to the Call graph tab --- .../MCPCallGraphPresenter.class.st | 89 ++++++++++++++++++- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st index 2c84672d..0d59ed12 100644 --- a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st @@ -5,17 +5,49 @@ Class { #name : 'MCPCallGraphPresenter', #superclass : 'SpPresenterWithModel', #instVars : [ - 'statusLabel' + 'statusLabel', + 'localSpansCheckBox', + 'refreshButton', + 'clearButton' ], #category : 'MCP-OpenTelemetry-UI', #package : 'MCP-OpenTelemetry-UI' } +{ #category : 'actions' } +MCPCallGraphPresenter >> clearSpans [ + + MCPOpenTelemetryObservabilityBackend localSpanStore clear. + self refreshView +] + +{ #category : 'initialization' } +MCPCallGraphPresenter >> connectPresenters [ + + localSpansCheckBox whenChangedDo: [ :enabled | self localSpansChangedTo: enabled ]. + refreshButton action: [ self refreshView ]. + clearButton action: [ self clearSpans ] +] + +{ #category : 'layout' } +MCPCallGraphPresenter >> controlsLayout [ + + ^ SpBoxLayout newLeftToRight + spacing: 8; + vAlignCenter; + add: localSpansCheckBox expand: false; + add: refreshButton expand: false; + add: clearButton expand: false; + yourself +] + { #category : 'layout' } MCPCallGraphPresenter >> defaultLayout [ ^ SpBoxLayout newTopToBottom + spacing: 6; borderWidth: 8; + add: self controlsLayout expand: false; add: statusLabel expand: false; yourself ] @@ -23,6 +55,59 @@ MCPCallGraphPresenter >> defaultLayout [ { #category : 'initialization' } MCPCallGraphPresenter >> initializePresenters [ + localSpansCheckBox := self newCheckBox. + refreshButton := self newButton. + clearButton := self newButton. statusLabel := self newLabel. - statusLabel label: 'Call graph: nothing to show yet.' + + localSpansCheckBox label: 'Keep spans in memory (nothing is exported)'. + refreshButton + label: 'Refresh'; + icon: (self iconNamed: #refreshCircling). + clearButton + label: 'Clear'; + icon: (self iconNamed: #trash) +] + +{ #category : 'actions' } +MCPCallGraphPresenter >> localSpansChangedTo: enabled [ + "The spans are made by the image's OpenTelemetry providers, which are global, so this turns them on for every server of the image; this one is switched to the OpenTelemetry backend, which makes them, when it records through another." + + | mcp | + mcp := self model ifNil: [ ^ self ]. + MCPOpenTelemetryObservabilityBackend isLocalSpansEnabled = enabled ifTrue: [ ^ self ]. + (enabled and: [ (mcp observability isKindOf: MCPOpenTelemetryObservabilityBackend) not ]) ifTrue: [ + mcp useOpenTelemetryObservability ]. + MCPOpenTelemetryObservabilityBackend useLocalSpans: enabled. + self refreshView +] + +{ #category : 'initialization' } +MCPCallGraphPresenter >> modelChanged [ + + self refreshView +] + +{ #category : 'updating' } +MCPCallGraphPresenter >> refreshView [ + + | mcp enabled | + mcp := self model ifNil: [ ^ self ]. + enabled := MCPOpenTelemetryObservabilityBackend isLocalSpansEnabled. + localSpansCheckBox state: enabled. + statusLabel label: (self statusFor: mcp enabled: enabled) +] + +{ #category : 'updating' } +MCPCallGraphPresenter >> statusFor: mcp enabled: enabled [ + + ^ String streamContents: [ :stream | + enabled + ifFalse: [ stream nextPutAll: 'Spans are not kept: turn it on to build the call graph.' ] + ifTrue: [ + stream + print: MCPOpenTelemetryObservabilityBackend localSpanStore size; + nextPutAll: ' spans kept'. + (mcp observability isKindOf: MCPOpenTelemetryObservabilityBackend) ifFalse: [ + stream nextPutAll: ' - this server does not record through OpenTelemetry' ] ] ] ] From f1a292a037a77ff7c2e3ea1f9aa2cf799cf4a30e Mon Sep 17 00:00:00 2001 From: alkalinan Date: Tue, 24 Nov 2026 13:00:58 +0100 Subject: [PATCH 04/11] Add an object-centric event log and directly-follows graphs built from tool-call spans --- .../MCPOcelLogTest.class.st | 179 ++++++++++++++++++ .../MCPOcelTestSpan.class.st | 103 ++++++++++ .../MCPOcelTestSpanContext.class.st | 24 +++ src/MCP-OpenTelemetry/MCPOcelEdge.class.st | 87 +++++++++ src/MCP-OpenTelemetry/MCPOcelEvent.class.st | 152 +++++++++++++++ .../MCPOcelFlowGraph.class.st | 97 ++++++++++ src/MCP-OpenTelemetry/MCPOcelLog.class.st | 109 +++++++++++ 7 files changed, 751 insertions(+) create mode 100644 src/MCP-OpenTelemetry-Tests/MCPOcelLogTest.class.st create mode 100644 src/MCP-OpenTelemetry-Tests/MCPOcelTestSpan.class.st create mode 100644 src/MCP-OpenTelemetry-Tests/MCPOcelTestSpanContext.class.st create mode 100644 src/MCP-OpenTelemetry/MCPOcelEdge.class.st create mode 100644 src/MCP-OpenTelemetry/MCPOcelEvent.class.st create mode 100644 src/MCP-OpenTelemetry/MCPOcelFlowGraph.class.st create mode 100644 src/MCP-OpenTelemetry/MCPOcelLog.class.st diff --git a/src/MCP-OpenTelemetry-Tests/MCPOcelLogTest.class.st b/src/MCP-OpenTelemetry-Tests/MCPOcelLogTest.class.st new file mode 100644 index 00000000..a276e6d3 --- /dev/null +++ b/src/MCP-OpenTelemetry-Tests/MCPOcelLogTest.class.st @@ -0,0 +1,179 @@ +" +The object-centric log and the directly-follows graphs read from the spans of tool calls. +" +Class { + #name : 'MCPOcelLogTest', + #superclass : 'TestCase', + #category : 'MCP-OpenTelemetry-Tests', + #package : 'MCP-OpenTelemetry-Tests' +} + +{ #category : 'running' } +MCPOcelLogTest >> dispatchingLog [ + "package_search, then tool_call dispatching class_search, then tool_call dispatching package_search, given out of order." + + ^ MCPOcelLog fromSpanSnapshots: { + (self + span: 'package_search' + id: 'e' + parent: 'd' + at: 61 + for: 3). + (self + span: 'tool_call' + id: 'd' + parent: nil + at: 60 + for: 5). + (self + span: 'class_search' + id: 'c' + parent: 'b' + at: 11 + for: 3). + (self + span: 'tool_call' + id: 'b' + parent: nil + at: 10 + for: 5). + (self + span: 'package_search' + id: 'a' + parent: nil + at: 0 + for: 4) } +] + +{ #category : 'running' } +MCPOcelLogTest >> failedSpan: aTool id: anId at: start for: duration [ + + ^ MCPOcelTestSpan + tool: aTool + id: anId + parent: nil + startMillisecond: start + durationMilliseconds: duration + session: 's1' + failed: true +] + +{ #category : 'running' } +MCPOcelLogTest >> span: aTool id: anId parent: aParent at: start for: duration [ + + ^ MCPOcelTestSpan + tool: aTool + id: anId + parent: aParent + startMillisecond: start + durationMilliseconds: duration + session: 's1' + failed: false +] + +{ #category : 'tests' } +MCPOcelLogTest >> testACallStartingWithItsDispatcherComesAfterIt [ + + | log | + log := MCPOcelLog fromSpanSnapshots: { + (self + span: 'class_search' + id: 'child' + parent: 'root' + at: 0 + for: 1). + (self + span: 'tool_call' + id: 'root' + parent: nil + at: 0 + for: 2) }. + self assert: (log events collect: #id) asArray equals: #( 'root' 'child' ). + self assert: (log events collect: #depth) asArray equals: #( 0 1 ) +] + +{ #category : 'tests' } +MCPOcelLogTest >> testASpanWhoseParentIsNotInTheLogIsARoot [ + + | log | + log := MCPOcelLog fromSpanSnapshots: { (self + span: 'class_search' + id: 'x' + parent: 'elsewhere' + at: 0 + for: 1) }. + self assert: log events first parentId isNil. + self assert: (log events first objectIdsOfType: 'tool') asArray equals: #( 'class_search' ) +] + +{ #category : 'tests' } +MCPOcelLogTest >> testActivitiesCarryHowManyCallsFailedAndHowLongTheyTook [ + + | graph | + graph := (MCPOcelLog fromSpanSnapshots: { + (self + span: 'class_get' + id: 'a' + parent: nil + at: 0 + for: 10). + (self + failedSpan: 'class_get' + id: 'b' + at: 20 + for: 30) }) flowGraphOfType: 'tool'. + self assert: (graph callCountOf: 'class_get') equals: 2. + self assert: (graph errorCountOf: 'class_get') equals: 1. + self assert: (graph meanDurationMillisecondsOf: 'class_get') equals: 20 +] + +{ #category : 'tests' } +MCPOcelLogTest >> testAnObjectTypeNoCallInvolvesHasAnEmptyGraph [ + + | graph | + graph := self dispatchingLog flowGraphOfType: 'client'. + self assert: graph activities isEmpty. + self assert: graph edges isEmpty +] + +{ #category : 'tests' } +MCPOcelLogTest >> testEventsFollowTheStartOfTheirCallWhateverTheOrderOfTheSpans [ + + self assert: (self dispatchingLog events collect: #id) asArray equals: #( 'a' 'b' 'c' 'd' 'e' ) +] + +{ #category : 'tests' } +MCPOcelLogTest >> testTheSessionGraphFollowsTheCallsOfASessionInTheOrderTheyStarted [ + + | graph edge | + graph := self dispatchingLog flowGraphOfType: 'session'. + self assert: graph edges size equals: 4. + edge := graph edgeFrom: 'package_search' to: 'tool_call'. + self assert: edge count equals: 1. + self assert: edge meanGapMilliseconds equals: 10. + self assert: edge objectCount equals: 1. + self assert: (graph edgeFrom: 'tool_call' to: 'class_search') meanGapMilliseconds equals: 1. + self assert: (graph edgeFrom: 'class_search' to: 'tool_call') meanGapMilliseconds equals: 49 +] + +{ #category : 'tests' } +MCPOcelLogTest >> testTheToolGraphFollowsEachToolThroughTheCallsThatInvolveIt [ + + | graph | + graph := self dispatchingLog flowGraphOfType: 'tool'. + self assert: graph activities equals: #( 'class_search' 'package_search' 'tool_call' ). + self assert: (graph edgeFrom: 'tool_call' to: 'class_search') count equals: 1. + self assert: (graph edgeFrom: 'class_search' to: 'tool_call') count equals: 1. + self assert: (graph edgeFrom: 'tool_call' to: 'package_search') count equals: 1. + self assert: (graph edgeFrom: 'package_search' to: 'package_search') count equals: 1. + self assert: (graph edgeFrom: 'tool_call' to: 'tool_call') isNil +] + +{ #category : 'tests' } +MCPOcelLogTest >> testTheToolThatDispatchedACallIsOneOfItsToolObjects [ + + | child | + child := self dispatchingLog events detect: [ :event | event id = 'c' ]. + self assert: (child objectIdsOfType: 'tool') asArray equals: #( 'class_search' 'tool_call' ). + self assert: (child objectIdsOfType: 'session') asArray equals: #( 's1' ) +] diff --git a/src/MCP-OpenTelemetry-Tests/MCPOcelTestSpan.class.st b/src/MCP-OpenTelemetry-Tests/MCPOcelTestSpan.class.st new file mode 100644 index 00000000..12f456aa --- /dev/null +++ b/src/MCP-OpenTelemetry-Tests/MCPOcelTestSpan.class.st @@ -0,0 +1,103 @@ +" +What a MCPOcelLog reads of a span snapshot, with the values given, so that a test says when each call started and ended without making spans. +" +Class { + #name : 'MCPOcelTestSpan', + #superclass : 'Object', + #instVars : [ + 'name', + 'spanId', + 'parentSpanContext', + 'startTime', + 'endTime', + 'attributes', + 'status' + ], + #category : 'MCP-OpenTelemetry-Tests', + #package : 'MCP-OpenTelemetry-Tests' +} + +{ #category : 'instance creation' } +MCPOcelTestSpan class >> tool: aToolName id: anId parent: aParentId startMillisecond: start durationMilliseconds: duration session: aSession failed: aBoolean [ + + ^ self new + setTool: aToolName + id: anId + parent: aParentId + startMillisecond: start + durationMilliseconds: duration + session: aSession + failed: aBoolean; + yourself +] + +{ #category : 'accessing' } +MCPOcelTestSpan >> attributes [ + + ^ attributes +] + +{ #category : 'accessing' } +MCPOcelTestSpan >> endTime [ + + ^ endTime +] + +{ #category : 'accessing' } +MCPOcelTestSpan >> name [ + + ^ name +] + +{ #category : 'accessing' } +MCPOcelTestSpan >> parentSpanContext [ + + ^ parentSpanContext +] + +{ #category : 'initialization' } +MCPOcelTestSpan >> setTool: aToolName id: anId parent: aParentId startMillisecond: start durationMilliseconds: duration session: aSession failed: aBoolean [ + "Times are milliseconds after a fixed instant." + + | origin | + origin := DateAndTime + year: 2026 + month: 1 + day: 1 + hour: 0 + minute: 0 + second: 0 + offset: Duration zero. + name := 'tools/call ' , aToolName. + spanId := anId. + parentSpanContext := aParentId ifNotNil: [ + MCPOcelTestSpanContext new + spanId: aParentId; + yourself ]. + startTime := origin + start milliSeconds. + endTime := startTime + duration milliSeconds. + attributes := { + ('gen_ai.tool.name' -> aToolName). + ('session.id' -> aSession) } asDictionary. + status := aBoolean + ifTrue: [ OTSpan error ] + ifFalse: [ OTSpan unset ] +] + +{ #category : 'accessing' } +MCPOcelTestSpan >> spanId [ + + ^ spanId +] + +{ #category : 'accessing' } +MCPOcelTestSpan >> startTime [ + + ^ startTime +] + +{ #category : 'accessing' } +MCPOcelTestSpan >> status [ + + ^ status +] diff --git a/src/MCP-OpenTelemetry-Tests/MCPOcelTestSpanContext.class.st b/src/MCP-OpenTelemetry-Tests/MCPOcelTestSpanContext.class.st new file mode 100644 index 00000000..7f2751ce --- /dev/null +++ b/src/MCP-OpenTelemetry-Tests/MCPOcelTestSpanContext.class.st @@ -0,0 +1,24 @@ +" +The span context of a MCPOcelTestSpan's parent: only the id of the parent's span, which is all a MCPOcelLog reads. +" +Class { + #name : 'MCPOcelTestSpanContext', + #superclass : 'Object', + #instVars : [ + 'spanId' + ], + #category : 'MCP-OpenTelemetry-Tests', + #package : 'MCP-OpenTelemetry-Tests' +} + +{ #category : 'accessing' } +MCPOcelTestSpanContext >> spanId [ + + ^ spanId +] + +{ #category : 'accessing' } +MCPOcelTestSpanContext >> spanId: aString [ + + spanId := aString +] diff --git a/src/MCP-OpenTelemetry/MCPOcelEdge.class.st b/src/MCP-OpenTelemetry/MCPOcelEdge.class.st new file mode 100644 index 00000000..bc058454 --- /dev/null +++ b/src/MCP-OpenTelemetry/MCPOcelEdge.class.st @@ -0,0 +1,87 @@ +" +An edge of the directly-follows graph of one object type: some object, in count cases in all, went from a call of the source activity directly to a call of the target activity, the next call that involved it. The gap is the time between the two calls' starts. +" +Class { + #name : 'MCPOcelEdge', + #superclass : 'Object', + #instVars : [ + 'source', + 'target', + 'count', + 'totalGapMilliseconds', + 'objectIds' + ], + #category : 'MCP-OpenTelemetry', + #package : 'MCP-OpenTelemetry' +} + +{ #category : 'instance creation' } +MCPOcelEdge class >> from: sourceActivity to: targetActivity [ + + ^ self new + setSource: sourceActivity target: targetActivity; + yourself +] + +{ #category : 'recording' } +MCPOcelEdge >> addCaseOfObject: anObjectId gapMilliseconds: aNumber [ + + count := count + 1. + totalGapMilliseconds := totalGapMilliseconds + aNumber. + objectIds add: anObjectId +] + +{ #category : 'accessing' } +MCPOcelEdge >> count [ + + ^ count +] + +{ #category : 'accessing' } +MCPOcelEdge >> isSelfLoop [ + + ^ source = target +] + +{ #category : 'accessing' } +MCPOcelEdge >> meanGapMilliseconds [ + + ^ count = 0 + ifTrue: [ 0 ] + ifFalse: [ totalGapMilliseconds / count ] +] + +{ #category : 'accessing' } +MCPOcelEdge >> objectCount [ + "How many different objects went this way." + + ^ objectIds size +] + +{ #category : 'accessing' } +MCPOcelEdge >> objectIds [ + + ^ objectIds +] + +{ #category : 'initialization' } +MCPOcelEdge >> setSource: sourceActivity target: targetActivity [ + + source := sourceActivity. + target := targetActivity. + count := 0. + totalGapMilliseconds := 0. + objectIds := Set new +] + +{ #category : 'accessing' } +MCPOcelEdge >> source [ + + ^ source +] + +{ #category : 'accessing' } +MCPOcelEdge >> target [ + + ^ target +] diff --git a/src/MCP-OpenTelemetry/MCPOcelEvent.class.st b/src/MCP-OpenTelemetry/MCPOcelEvent.class.st new file mode 100644 index 00000000..f64968b8 --- /dev/null +++ b/src/MCP-OpenTelemetry/MCPOcelEvent.class.st @@ -0,0 +1,152 @@ +" +One tool call of an object-centric event log (OCEL): the activity is the tool called, and the event relates to the objects it involves, by object type: the tool called, and the tool that dispatched the call when one did (type 'tool', the central object), the session it belongs to ('session') and the client that made it ('client'). It is read from the span of the call, whose id it keeps. +" +Class { + #name : 'MCPOcelEvent', + #superclass : 'Object', + #instVars : [ + 'id', + 'activity', + 'startedAt', + 'finishedAt', + 'isError', + 'dispatchPath', + 'parentId', + 'depth', + 'objects' + ], + #category : 'MCP-OpenTelemetry', + #package : 'MCP-OpenTelemetry' +} + +{ #category : 'accessing' } +MCPOcelEvent >> activity [ + + ^ activity +] + +{ #category : 'accessing' } +MCPOcelEvent >> activity: aString [ + + activity := aString +] + +{ #category : 'objects' } +MCPOcelEvent >> addObject: anId ofType: aType [ + + | ids | + ids := self objects at: aType ifAbsentPut: [ OrderedCollection new ]. + (ids includes: anId) ifFalse: [ ids add: anId ] +] + +{ #category : 'accessing' } +MCPOcelEvent >> depth [ + + ^ depth ifNil: [ 0 ] +] + +{ #category : 'accessing' } +MCPOcelEvent >> depth: anInteger [ + + depth := anInteger +] + +{ #category : 'accessing' } +MCPOcelEvent >> dispatchPath [ + + ^ dispatchPath +] + +{ #category : 'accessing' } +MCPOcelEvent >> dispatchPath: aString [ + + dispatchPath := aString +] + +{ #category : 'accessing' } +MCPOcelEvent >> durationMilliseconds [ + "How long the call took, 0 when it has no end." + + ^ (startedAt isNil or: [ finishedAt isNil ]) + ifTrue: [ 0 ] + ifFalse: [ (finishedAt - startedAt) asMilliSeconds ] +] + +{ #category : 'accessing' } +MCPOcelEvent >> finishedAt [ + + ^ finishedAt +] + +{ #category : 'accessing' } +MCPOcelEvent >> finishedAt: aDateAndTime [ + + finishedAt := aDateAndTime +] + +{ #category : 'accessing' } +MCPOcelEvent >> id [ + + ^ id +] + +{ #category : 'accessing' } +MCPOcelEvent >> id: aString [ + + id := aString +] + +{ #category : 'objects' } +MCPOcelEvent >> involvesObjectType: aType [ + + ^ (self objectIdsOfType: aType) isNotEmpty +] + +{ #category : 'accessing' } +MCPOcelEvent >> isError [ + + ^ isError == true +] + +{ #category : 'accessing' } +MCPOcelEvent >> isError: aBoolean [ + + isError := aBoolean +] + +{ #category : 'objects' } +MCPOcelEvent >> objectIdsOfType: aType [ + + ^ self objects at: aType ifAbsent: [ #( ) ] +] + +{ #category : 'objects' } +MCPOcelEvent >> objects [ + "The ids of the objects the event involves, by object type." + + ^ objects ifNil: [ objects := Dictionary new ] +] + +{ #category : 'accessing' } +MCPOcelEvent >> parentId [ + + ^ parentId +] + +{ #category : 'accessing' } +MCPOcelEvent >> parentId: aString [ + + parentId := aString +] + +{ #category : 'accessing' } +MCPOcelEvent >> startedAt [ + + ^ startedAt +] + +{ #category : 'accessing' } +MCPOcelEvent >> startedAt: aDateAndTime [ + + startedAt := aDateAndTime +] diff --git a/src/MCP-OpenTelemetry/MCPOcelFlowGraph.class.st b/src/MCP-OpenTelemetry/MCPOcelFlowGraph.class.st new file mode 100644 index 00000000..e02d054c --- /dev/null +++ b/src/MCP-OpenTelemetry/MCPOcelFlowGraph.class.st @@ -0,0 +1,97 @@ +" +The directly-follows graph of one object type of a MCPOcelLog, in the sense of object-centric process mining: each object of the type has the sequence of the calls that involve it, in the order of their start, and the graph counts which activity follows which in those sequences. The activities are the tools called; they carry how many calls, how many failed and how long they took, over the calls that involve an object of the type. +" +Class { + #name : 'MCPOcelFlowGraph', + #superclass : 'Object', + #instVars : [ + 'objectType', + 'edges', + 'activityCounts', + 'activityErrorCounts', + 'activityTotalDurations' + ], + #category : 'MCP-OpenTelemetry', + #package : 'MCP-OpenTelemetry' +} + +{ #category : 'instance creation' } +MCPOcelFlowGraph class >> ofType: anObjectType in: anOcelLog [ + + ^ self new + buildType: anObjectType from: anOcelLog; + yourself +] + +{ #category : 'accessing' } +MCPOcelFlowGraph >> activities [ + "The tools called, by name." + + ^ activityCounts keys sorted +] + +{ #category : 'building' } +MCPOcelFlowGraph >> buildType: anObjectType from: anOcelLog [ + "Flattens the log on the type: each object of it has the calls that involve it in the order of their start, and each two that follow one another make a case of the edge between their activities." + + objectType := anObjectType. + edges := Dictionary new. + activityCounts := Dictionary new. + activityErrorCounts := Dictionary new. + activityTotalDurations := Dictionary new. + (anOcelLog events select: [ :event | event involvesObjectType: anObjectType ]) do: [ :event | + activityCounts at: event activity put: (activityCounts at: event activity ifAbsent: [ 0 ]) + 1. + activityTotalDurations + at: event activity + put: (activityTotalDurations at: event activity ifAbsent: [ 0 ]) + event durationMilliseconds. + event isError ifTrue: [ + activityErrorCounts at: event activity put: (activityErrorCounts at: event activity ifAbsent: [ 0 ]) + 1 ] ]. + (anOcelLog objectIdsOfType: anObjectType) do: [ :objectId | + | sequence | + sequence := anOcelLog eventsOfObject: objectId type: anObjectType. + sequence overlappingPairsDo: [ :before :after | + (edges at: before activity -> after activity ifAbsentPut: [ MCPOcelEdge from: before activity to: after activity ]) + addCaseOfObject: objectId + gapMilliseconds: (after startedAt - before startedAt) asMilliSeconds ] ] +] + +{ #category : 'accessing' } +MCPOcelFlowGraph >> callCountOf: anActivity [ + + ^ activityCounts at: anActivity ifAbsent: [ 0 ] +] + +{ #category : 'accessing' } +MCPOcelFlowGraph >> edgeFrom: source to: target [ + + ^ edges at: source -> target ifAbsent: [ nil ] +] + +{ #category : 'accessing' } +MCPOcelFlowGraph >> edges [ + "The edges, most followed first." + + ^ edges values asSortedCollection: [ :a :b | a count > b count or: [ a count = b count and: [ a source <= b source ] ] ] +] + +{ #category : 'accessing' } +MCPOcelFlowGraph >> errorCountOf: anActivity [ + + ^ activityErrorCounts at: anActivity ifAbsent: [ 0 ] +] + +{ #category : 'accessing' } +MCPOcelFlowGraph >> meanDurationMillisecondsOf: anActivity [ + + | calls | + calls := self callCountOf: anActivity. + ^ calls = 0 + ifTrue: [ 0 ] + ifFalse: [ (activityTotalDurations at: anActivity) / calls ] +] + +{ #category : 'accessing' } +MCPOcelFlowGraph >> objectType [ + + ^ objectType +] diff --git a/src/MCP-OpenTelemetry/MCPOcelLog.class.st b/src/MCP-OpenTelemetry/MCPOcelLog.class.st new file mode 100644 index 00000000..b2960a36 --- /dev/null +++ b/src/MCP-OpenTelemetry/MCPOcelLog.class.st @@ -0,0 +1,109 @@ +" +An object-centric event log of tool calls, built from the spans an image kept (MCPOpenTelemetryLocalSpanStore): one event per call, in the order of their start, related to the objects they involve. The central object type is the tool: a call involves the tool it calls and, when another tool dispatched it (tool_call), that tool too, so the sequence of a dispatching tool holds the calls it made. Spans whose parent is not in the log, because it is another system's or it was dropped, are roots. +" +Class { + #name : 'MCPOcelLog', + #superclass : 'Object', + #instVars : [ + 'events' + ], + #category : 'MCP-OpenTelemetry', + #package : 'MCP-OpenTelemetry' +} + +{ #category : 'instance creation' } +MCPOcelLog class >> fromSpanSnapshots: spanSnapshots [ + "The log of the tool calls the spans describe, whatever order they come in." + + ^ self new + readSpanSnapshots: spanSnapshots; + yourself +] + +{ #category : 'reading' } +MCPOcelLog >> depthOf: anEvent in: eventsById [ + "How many calls dispatched this one, one dispatching the next." + + | depth current | + depth := 0. + current := anEvent. + [ current parentId isNotNil and: [ depth < 100 ] ] whileTrue: [ + current := eventsById at: current parentId. + depth := depth + 1 ]. + ^ depth +] + +{ #category : 'reading' } +MCPOcelLog >> eventFor: aSpanSnapshot [ + "What the span of a call says: the tool called, when it started and ended, whether it failed, how it was dispatched, the span of the call that dispatched it, and the objects the call involves, but for the dispatching tool, which the log knows." + + | attributes event | + attributes := aSpanSnapshot attributes. + event := MCPOcelEvent new + id: aSpanSnapshot spanId; + activity: + ((attributes at: 'gen_ai.tool.name' ifAbsent: [ nil ]) ifNil: [ aSpanSnapshot name withoutPrefix: 'tools/call ' ]); + startedAt: aSpanSnapshot startTime; + finishedAt: aSpanSnapshot endTime; + isError: aSpanSnapshot status = OTSpan error; + dispatchPath: (attributes at: 'pharo.mcp.dispatch_path' ifAbsent: [ nil ]); + parentId: (aSpanSnapshot parentSpanContext ifNotNil: [ :context | context spanId ]); + yourself. + event addObject: event activity ofType: 'tool'. + attributes at: 'session.id' ifPresent: [ :session | event addObject: session ofType: 'session' ]. + attributes at: 'pharo.mcp.client.name' ifPresent: [ :client | event addObject: client ofType: 'client' ]. + ^ event +] + +{ #category : 'accessing' } +MCPOcelLog >> events [ + "The calls, in the order of their start; a call comes after the call that dispatched it." + + ^ events ifNil: [ #( ) ] +] + +{ #category : 'accessing' } +MCPOcelLog >> eventsOfObject: anId type: aType [ + + ^ events select: [ :event | (event objectIdsOfType: aType) includes: anId ] +] + +{ #category : 'accessing' } +MCPOcelLog >> flowGraphOfType: anObjectType [ + + ^ MCPOcelFlowGraph ofType: anObjectType in: self +] + +{ #category : 'initialization' } +MCPOcelLog >> initialize [ + + super initialize. + events := OrderedCollection new +] + +{ #category : 'accessing' } +MCPOcelLog >> objectIdsOfType: aType [ + + ^ (self events flatCollect: [ :event | event objectIdsOfType: aType ] as: Set) sorted +] + +{ #category : 'accessing' } +MCPOcelLog >> objectTypes [ + + ^ #( 'tool' 'session' 'client' ) +] + +{ #category : 'reading' } +MCPOcelLog >> readSpanSnapshots: spanSnapshots [ + "One event per span, ordered by the start of its call, a call after the call that dispatched it when both started at the same time. The tool that dispatched a call is one of its tool objects, when its span is in the log." + + | byId | + events := (spanSnapshots collect: [ :snapshot | self eventFor: snapshot ]) asOrderedCollection. + byId := Dictionary new. + events do: [ :event | byId at: event id put: event ]. + events do: [ :event | event parentId ifNotNil: [ :parentId | byId at: parentId ifAbsent: [ event parentId: nil ] ] ]. + events do: [ :event | event depth: (self depthOf: event in: byId) ]. + events do: [ :event | event parentId ifNotNil: [ :parentId | event addObject: (byId at: parentId) activity ofType: 'tool' ] ]. + events := (events sorted: [ :a :b | a startedAt < b startedAt or: [ a startedAt = b startedAt and: [ a depth <= b depth ] ] ]) + asOrderedCollection +] From 93d148372ad2fa350431681719d64d5fef584da4 Mon Sep 17 00:00:00 2001 From: alkalinan Date: Tue, 24 Nov 2026 13:19:56 +0100 Subject: [PATCH 05/11] Order the directly-follows activities by first call and compute their layers Draw the directly-follows graph of the Call graph tab with Roassal --- .../MCPOcelLogTest.class.st | 67 ++++++++ .../MCPCallGraphDrawing.class.st | 146 ++++++++++++++++++ .../MCPCallGraphPresenter.class.st | 126 ++++++++++++++- .../MCPOcelFlowGraph.class.st | 48 +++++- 4 files changed, 371 insertions(+), 16 deletions(-) create mode 100644 src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st diff --git a/src/MCP-OpenTelemetry-Tests/MCPOcelLogTest.class.st b/src/MCP-OpenTelemetry-Tests/MCPOcelLogTest.class.st index a276e6d3..774c6d00 100644 --- a/src/MCP-OpenTelemetry-Tests/MCPOcelLogTest.class.st +++ b/src/MCP-OpenTelemetry-Tests/MCPOcelLogTest.class.st @@ -127,6 +127,38 @@ MCPOcelLogTest >> testActivitiesCarryHowManyCallsFailedAndHowLongTheyTook [ self assert: (graph meanDurationMillisecondsOf: 'class_get') equals: 20 ] +{ #category : 'tests' } +MCPOcelLogTest >> testActivitiesComeInTheOrderOfTheirFirstCall [ + + self + assert: (self dispatchingLog flowGraphOfType: 'tool') activitiesByFirstCall + equals: #( 'package_search' 'tool_call' 'class_search' ) +] + +{ #category : 'tests' } +MCPOcelLogTest >> testAnActivityNoChainReachesStartsAtTheFirstLayer [ + + | log layers | + log := MCPOcelLog fromSpanSnapshots: { + (self + span: 'a' + id: '1' + parent: nil + at: 0 + for: 1). + (MCPOcelTestSpan + tool: 'z' + id: '2' + parent: nil + startMillisecond: 5 + durationMilliseconds: 1 + session: 's2' + failed: false) }. + layers := (log flowGraphOfType: 'session') layers. + self assert: (layers at: 'a') equals: 0. + self assert: (layers at: 'z') equals: 0 +] + { #category : 'tests' } MCPOcelLogTest >> testAnObjectTypeNoCallInvolvesHasAnEmptyGraph [ @@ -142,6 +174,41 @@ MCPOcelLogTest >> testEventsFollowTheStartOfTheirCallWhateverTheOrderOfTheSpans self assert: (self dispatchingLog events collect: #id) asArray equals: #( 'a' 'b' 'c' 'd' 'e' ) ] +{ #category : 'tests' } +MCPOcelLogTest >> testLayersGoTheWayTheCallsDidAndIgnoreCycles [ + + | log layers | + log := MCPOcelLog fromSpanSnapshots: { + (self + span: 'a' + id: '1' + parent: nil + at: 0 + for: 1). + (self + span: 'b' + id: '2' + parent: nil + at: 10 + for: 1). + (self + span: 'c' + id: '3' + parent: nil + at: 20 + for: 1). + (self + span: 'b' + id: '4' + parent: nil + at: 30 + for: 1) }. + layers := (log flowGraphOfType: 'session') layers. + self assert: (layers at: 'a') equals: 0. + self assert: (layers at: 'b') equals: 1. + self assert: (layers at: 'c') equals: 2 +] + { #category : 'tests' } MCPOcelLogTest >> testTheSessionGraphFollowsTheCallsOfASessionInTheOrderTheyStarted [ diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st new file mode 100644 index 00000000..5189564f --- /dev/null +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st @@ -0,0 +1,146 @@ +" +Draws a MCPOcelFlowGraph on a Roassal canvas: a box per tool, from the left in the order the calls went, and an arrow per directly-follows edge, thicker the more cases it has. A tool that follows itself shows how many times in its box rather than as an arrow, and a tool with failed calls has a red border. Hovering a box or an arrow says its numbers. +" +Class { + #name : 'MCPCallGraphDrawing', + #superclass : 'Object', + #instVars : [ + 'flowGraph', + 'nodes' + ], + #category : 'MCP-OpenTelemetry-UI', + #package : 'MCP-OpenTelemetry-UI' +} + +{ #category : 'drawing' } +MCPCallGraphDrawing class >> drawFlowGraph: aFlowGraph on: aCanvas [ + "Replaces what aCanvas shows with the graph." + + aCanvas shapes copy do: [ :shape | shape remove ]. + ^ self new + flowGraph: aFlowGraph; + drawOn: aCanvas; + yourself +] + +{ #category : 'drawing' } +MCPCallGraphDrawing >> describe: anActivity [ + + ^ String streamContents: [ :stream | + stream + nextPutAll: anActivity; + cr; + print: (flowGraph callCountOf: anActivity); + nextPutAll: ' calls, '; + print: (flowGraph errorCountOf: anActivity); + nextPutAll: ' failed, '; + nextPutAll: ((flowGraph meanDurationMillisecondsOf: anActivity) asFloat printShowingDecimalPlaces: 1); + nextPutAll: ' ms on average' ] +] + +{ #category : 'drawing' } +MCPCallGraphDrawing >> describeEdge: anEdge [ + + ^ String streamContents: [ :stream | + stream + nextPutAll: anEdge source; + nextPutAll: ' directly followed by '; + nextPutAll: anEdge target; + cr; + print: anEdge count; + nextPutAll: ' times, by '; + print: anEdge objectCount; + nextPutAll: ' objects, '; + nextPutAll: (anEdge meanGapMilliseconds asFloat printShowingDecimalPlaces: 1); + nextPutAll: ' ms between starts on average' ] +] + +{ #category : 'drawing' } +MCPCallGraphDrawing >> drawEdgesOn: aCanvas [ + + | arrows | + arrows := flowGraph edges reject: [ :edge | edge isSelfLoop ]. + arrows isEmpty ifTrue: [ ^ self ]. + RSLineBuilder arrowedLine + canvas: aCanvas; + withBorderAttachPoint; + color: (Color gray alpha: 0.8); + shapes: nodes; + useAssociations: (arrows collect: [ :edge | edge source -> edge target ] as: Array). + aCanvas edges do: [ :line | + | edge | + edge := flowGraph edgeFrom: line model key to: line model value. + line + width: 1 + (edge count log: 2); + popupText: [ :each | self describeEdge: edge ] ] +] + +{ #category : 'drawing' } +MCPCallGraphDrawing >> drawOn: aCanvas [ + + nodes := flowGraph activitiesByFirstCall collect: [ :activity | self nodeFor: activity ]. + aCanvas addAll: nodes. + self drawEdgesOn: aCanvas. + self layOutNodes +] + +{ #category : 'accessing' } +MCPCallGraphDrawing >> flowGraph: aFlowGraph [ + + flowGraph := aFlowGraph +] + +{ #category : 'drawing' } +MCPCallGraphDrawing >> labelOf: anActivity [ + "The tool, and how many times it follows itself when it does." + + ^ (flowGraph edgeFrom: anActivity to: anActivity) ifNil: [ anActivity ] ifNotNil: [ :loop | + String streamContents: [ :stream | + stream + nextPutAll: anActivity; + nextPutAll: ' (again x'; + print: loop count; + nextPut: $) ] ] +] + +{ #category : 'layout' } +MCPCallGraphDrawing >> layOutNodes [ + "A column per layer, from the left, its boxes one under the other in the order of their first call, centered on the middle." + + | layers columnWidth rowHeight | + layers := flowGraph layers. + columnWidth := (nodes inject: 0 into: [ :widest :node | widest max: node width ]) + 90. + rowHeight := 60. + (nodes groupedBy: [ :node | layers at: node model ]) keysAndValuesDo: [ :layer :column | + column withIndexDo: [ :node :index | node position: layer * columnWidth @ (index - 1 - (column size - 1 / 2) * rowHeight) ] ] +] + +{ #category : 'drawing' } +MCPCallGraphDrawing >> nodeFor: anActivity [ + + | label box errors | + errors := flowGraph errorCountOf: anActivity. + label := RSLabel new + text: (self labelOf: anActivity); + yourself. + box := RSBox new + extent: label textWidth + 20 @ 28; + color: Color white; + border: (RSBorder new + color: (errors > 0 + ifTrue: [ Color red ] + ifFalse: [ Color gray ]); + width: (errors > 0 + ifTrue: [ 2 ] + ifFalse: [ 1 ]); + yourself); + cornerRadius: 6; + yourself. + ^ RSComposite new + model: anActivity; + shapes: { + box. + label }; + popupText: [ :activity | self describe: activity ]; + yourself +] diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st index 0d59ed12..842b006c 100644 --- a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st @@ -8,7 +8,14 @@ Class { 'statusLabel', 'localSpansCheckBox', 'refreshButton', - 'clearButton' + 'clearButton', + 'objectTypeDropList', + 'activitiesLabel', + 'activitiesTable', + 'edgesLabel', + 'edgesTable', + 'flowGraph', + 'graphPresenter' ], #category : 'MCP-OpenTelemetry-UI', #package : 'MCP-OpenTelemetry-UI' @@ -25,6 +32,7 @@ MCPCallGraphPresenter >> clearSpans [ MCPCallGraphPresenter >> connectPresenters [ localSpansCheckBox whenChangedDo: [ :enabled | self localSpansChangedTo: enabled ]. + objectTypeDropList whenSelectedItemChangedDo: [ :type | self refreshView ]. refreshButton action: [ self refreshView ]. clearButton action: [ self clearSpans ] ] @@ -36,11 +44,19 @@ MCPCallGraphPresenter >> controlsLayout [ spacing: 8; vAlignCenter; add: localSpansCheckBox expand: false; + add: objectTypeDropList expand: false; add: refreshButton expand: false; add: clearButton expand: false; yourself ] +{ #category : 'updating' } +MCPCallGraphPresenter >> currentFlowGraph [ + "The graph the tables show: of the object type chosen, over the spans kept when it was last refreshed." + + ^ flowGraph ifNil: [ flowGraph := MCPOcelFlowGraph ofType: 'tool' in: MCPOcelLog new ] +] + { #category : 'layout' } MCPCallGraphPresenter >> defaultLayout [ @@ -49,24 +65,69 @@ MCPCallGraphPresenter >> defaultLayout [ borderWidth: 8; add: self controlsLayout expand: false; add: statusLabel expand: false; + add: self sectionsLayout; yourself ] +{ #category : 'updating' } +MCPCallGraphPresenter >> drawGraph [ + "Draws the graph of the last refresh. Setting the script redraws, so a new block each time; the canvas gets its controller, for zoom and drag, once." + + | graph | + graph := flowGraph. + graphPresenter script: [ :canvas | + MCPCallGraphDrawing drawFlowGraph: graph on: canvas. + canvas controllerInteraction ifNil: [ canvas @ RSCanvasController ] ] +] + { #category : 'initialization' } MCPCallGraphPresenter >> initializePresenters [ localSpansCheckBox := self newCheckBox. + objectTypeDropList := self newDropList. refreshButton := self newButton. clearButton := self newButton. statusLabel := self newLabel. - - localSpansCheckBox label: 'Keep spans in memory (nothing is exported)'. + graphPresenter := self newRoassal. + activitiesLabel := self newLabel. + activitiesTable := self newTable. + edgesLabel := self newLabel. + edgesTable := self newTable. + + localSpansCheckBox label: 'Keep spans (no export)'. + objectTypeDropList + items: MCPOcelLog new objectTypes; + display: [ :type | 'Object: ' , type ]. refreshButton label: 'Refresh'; icon: (self iconNamed: #refreshCircling). clearButton label: 'Clear'; - icon: (self iconNamed: #trash) + icon: (self iconNamed: #trash). + self initializeTables +] + +{ #category : 'initialization' } +MCPCallGraphPresenter >> initializeTables [ + + activitiesTable + addColumn: (SpStringTableColumn title: 'Tool' evaluated: [ :activity | activity ]); + addColumn: + (SpStringTableColumn title: 'Calls' evaluated: [ :activity | (self currentFlowGraph callCountOf: activity) asString ]); + addColumn: + (SpStringTableColumn title: 'Errors' evaluated: [ :activity | (self currentFlowGraph errorCountOf: activity) asString ]); + addColumn: (SpStringTableColumn + title: 'Mean ms' + evaluated: [ :activity | (self currentFlowGraph meanDurationMillisecondsOf: activity) asFloat printShowingDecimalPlaces: 1 ]); + beResizable. + edgesTable + addColumn: (SpStringTableColumn title: 'From' evaluated: #source); + addColumn: (SpStringTableColumn title: 'To' evaluated: #target); + addColumn: (SpStringTableColumn title: 'Cases' evaluated: [ :edge | edge count asString ]); + addColumn: (SpStringTableColumn title: 'Objects' evaluated: [ :edge | edge objectCount asString ]); + addColumn: + (SpStringTableColumn title: 'Mean gap ms' evaluated: [ :edge | edge meanGapMilliseconds asFloat printShowingDecimalPlaces: 1 ]); + beResizable ] { #category : 'actions' } @@ -91,15 +152,61 @@ MCPCallGraphPresenter >> modelChanged [ { #category : 'updating' } MCPCallGraphPresenter >> refreshView [ - | mcp enabled | + | mcp enabled log type | mcp := self model ifNil: [ ^ self ]. enabled := MCPOpenTelemetryObservabilityBackend isLocalSpansEnabled. localSpansCheckBox state: enabled. - statusLabel label: (self statusFor: mcp enabled: enabled) + log := MCPOcelLog fromSpanSnapshots: MCPOpenTelemetryObservabilityBackend localSpanStore snapshots. + type := objectTypeDropList selectedItem ifNil: [ 'tool' ]. + flowGraph := log flowGraphOfType: type. + statusLabel label: (self statusFor: mcp enabled: enabled events: log events size). + activitiesLabel label: (self sectionLabelFor: 'Tools' count: flowGraph activities size type: type). + activitiesTable items: flowGraph activities. + edgesLabel label: (self sectionLabelFor: 'Directly follows' count: flowGraph edges size type: type). + edgesTable items: flowGraph edges asArray. + self drawGraph ] { #category : 'updating' } -MCPCallGraphPresenter >> statusFor: mcp enabled: enabled [ +MCPCallGraphPresenter >> sectionLabelFor: aTitle count: aCount type: anObjectType [ + + ^ String streamContents: [ :stream | + stream + nextPutAll: aTitle; + nextPutAll: ' ('; + print: aCount; + nextPutAll: ') - flow of '; + nextPutAll: anObjectType; + nextPutAll: ' objects' ] +] + +{ #category : 'layout' } +MCPCallGraphPresenter >> sectionLayoutFor: aLabel table: aTable [ + + ^ SpBoxLayout newTopToBottom + spacing: 2; + add: aLabel expand: false; + add: aTable; + yourself +] + +{ #category : 'layout' } +MCPCallGraphPresenter >> sectionsLayout [ + "The graph, then the numbers it is drawn from." + + ^ SpPanedLayout newTopToBottom + positionOfSlider: 55 percent; + add: graphPresenter; + add: (SpPanedLayout newTopToBottom + positionOfSlider: 40 percent; + add: (self sectionLayoutFor: activitiesLabel table: activitiesTable); + add: (self sectionLayoutFor: edgesLabel table: edgesTable); + yourself); + yourself +] + +{ #category : 'updating' } +MCPCallGraphPresenter >> statusFor: mcp enabled: enabled events: eventCount [ ^ String streamContents: [ :stream | enabled @@ -107,7 +214,10 @@ MCPCallGraphPresenter >> statusFor: mcp enabled: enabled [ ifTrue: [ stream print: MCPOpenTelemetryObservabilityBackend localSpanStore size; - nextPutAll: ' spans kept'. + nextPutAll: ' spans kept, '. + stream + print: eventCount; + nextPutAll: ' calls'. (mcp observability isKindOf: MCPOpenTelemetryObservabilityBackend) ifFalse: [ stream nextPutAll: ' - this server does not record through OpenTelemetry' ] ] ] ] diff --git a/src/MCP-OpenTelemetry/MCPOcelFlowGraph.class.st b/src/MCP-OpenTelemetry/MCPOcelFlowGraph.class.st index e02d054c..4b9f2895 100644 --- a/src/MCP-OpenTelemetry/MCPOcelFlowGraph.class.st +++ b/src/MCP-OpenTelemetry/MCPOcelFlowGraph.class.st @@ -9,7 +9,8 @@ Class { 'edges', 'activityCounts', 'activityErrorCounts', - 'activityTotalDurations' + 'activityTotalDurations', + 'activityFirstStarts' ], #category : 'MCP-OpenTelemetry', #package : 'MCP-OpenTelemetry' @@ -30,6 +31,15 @@ MCPOcelFlowGraph >> activities [ ^ activityCounts keys sorted ] +{ #category : 'accessing' } +MCPOcelFlowGraph >> activitiesByFirstCall [ + "The tools called, the one called first first. The log is in the order of the calls' start, which an activity inherits from its first call." + + ^ activityFirstStarts keys sorted: [ :a :b | + (activityFirstStarts at: a) < (activityFirstStarts at: b) or: [ + (activityFirstStarts at: a) = (activityFirstStarts at: b) and: [ a <= b ] ] ] +] + { #category : 'building' } MCPOcelFlowGraph >> buildType: anObjectType from: anOcelLog [ "Flattens the log on the type: each object of it has the calls that involve it in the order of their start, and each two that follow one another make a case of the edge between their activities." @@ -39,13 +49,16 @@ MCPOcelFlowGraph >> buildType: anObjectType from: anOcelLog [ activityCounts := Dictionary new. activityErrorCounts := Dictionary new. activityTotalDurations := Dictionary new. - (anOcelLog events select: [ :event | event involvesObjectType: anObjectType ]) do: [ :event | - activityCounts at: event activity put: (activityCounts at: event activity ifAbsent: [ 0 ]) + 1. - activityTotalDurations - at: event activity - put: (activityTotalDurations at: event activity ifAbsent: [ 0 ]) + event durationMilliseconds. - event isError ifTrue: [ - activityErrorCounts at: event activity put: (activityErrorCounts at: event activity ifAbsent: [ 0 ]) + 1 ] ]. + activityFirstStarts := Dictionary new. + anOcelLog events do: [ :event | + (event involvesObjectType: anObjectType) ifTrue: [ + activityCounts at: event activity put: (activityCounts at: event activity ifAbsent: [ 0 ]) + 1. + activityTotalDurations + at: event activity + put: (activityTotalDurations at: event activity ifAbsent: [ 0 ]) + event durationMilliseconds. + activityFirstStarts at: event activity ifAbsentPut: [ event startedAt ]. + event isError ifTrue: [ + activityErrorCounts at: event activity put: (activityErrorCounts at: event activity ifAbsent: [ 0 ]) + 1 ] ] ]. (anOcelLog objectIdsOfType: anObjectType) do: [ :objectId | | sequence | sequence := anOcelLog eventsOfObject: objectId type: anObjectType. @@ -80,6 +93,25 @@ MCPOcelFlowGraph >> errorCountOf: anActivity [ ^ activityErrorCounts at: anActivity ifAbsent: [ 0 ] ] +{ #category : 'layout' } +MCPOcelFlowGraph >> layers [ + "The layer each activity is drawn in, from the left: the longest chain of edges that reaches it from an activity called before it, going from the activity called first. An edge that returns to an activity of the chain being followed, a cycle, is not followed, so that the layers go the way the calls did. An activity the first ones do not reach starts a chain of its own, at layer 0." + + | layers onChain follow | + layers := Dictionary new. + onChain := Set new. + follow := nil. + follow := [ :activity :layer | + ((onChain includes: activity) not and: [ (layers at: activity ifAbsent: [ -1 ]) < layer ]) ifTrue: [ + layers at: activity put: layer. + onChain add: activity. + (edges values select: [ :edge | edge source = activity and: [ edge isSelfLoop not ] ]) do: [ :edge | + follow value: edge target value: layer + 1 ]. + onChain remove: activity ] ]. + self activitiesByFirstCall do: [ :activity | layers at: activity ifAbsent: [ follow value: activity value: 0 ] ]. + ^ layers +] + { #category : 'accessing' } MCPOcelFlowGraph >> meanDurationMillisecondsOf: anActivity [ From 3f82334d51452fd32018a7d131a7caf0f6b2e47e Mon Sep 17 00:00:00 2001 From: alkalinan Date: Tue, 24 Nov 2026 13:29:42 +0100 Subject: [PATCH 06/11] Make the OCEL graph interactive: drag, hover highlight, and selection shared with the tables Keep the local-spans setting out of the way of the OpenTelemetry backend tests --- ...TelemetryObservabilityBackendTest.class.st | 8 +- src/MCP-OpenTelemetry-UI/MCP.extension.st | 2 +- .../MCPCallGraphDrawing.class.st | 231 ++++++++++++++++-- .../MCPCallGraphPresenter.class.st | 72 +++++- 4 files changed, 281 insertions(+), 32 deletions(-) diff --git a/src/MCP-OpenTelemetry-Tests/MCPOpenTelemetryObservabilityBackendTest.class.st b/src/MCP-OpenTelemetry-Tests/MCPOpenTelemetryObservabilityBackendTest.class.st index dca52cfe..d2fe0fa0 100644 --- a/src/MCP-OpenTelemetry-Tests/MCPOpenTelemetryObservabilityBackendTest.class.st +++ b/src/MCP-OpenTelemetry-Tests/MCPOpenTelemetryObservabilityBackendTest.class.st @@ -23,7 +23,8 @@ Class { 'previousSpanExporter', 'previousDefaultBackendClass', 'previousProviderState', - 'previousEnvironment' + 'previousEnvironment', + 'previousLocalSpans' ], #category : 'MCP-OpenTelemetry-Tests', #package : 'MCP-OpenTelemetry-Tests' @@ -202,10 +203,12 @@ MCPOpenTelemetryObservabilityBackendTest >> sessionOfACallAt: aDateAndTime conte { #category : 'running' } MCPOpenTelemetryObservabilityBackendTest >> setUp [ - "The backend under test is configured as a server configures it, from settings that ask for traces, in an environment from which nothing made sends anything." + "The backend under test is configured as a server configures it, from settings that ask for traces, in an environment from which nothing made sends anything. The image may keep its spans for itself, which it does not while a test runs, so that settings asking for no traces mean none." super setUp. self isolateEnvironment. + previousLocalSpans := MCPOpenTelemetryObservabilityBackend isLocalSpansEnabled. + (MCPOpenTelemetryObservabilityBackend classVariableNamed: #LocalSpansEnabled) value: false. previousTracerProvider := (OTTracerProvider classVariableNamed: #Current) value. previousMeterProvider := OTMeterProvider currentOrNil. previousLoggerProvider := OTLoggerProvider currentOrNil. @@ -322,6 +325,7 @@ MCPOpenTelemetryObservabilityBackendTest >> tearDown [ self providerState with: previousProviderState do: [ :each :value | each value: value ]. self registry value: previousBackends. self defaultBackendClass value: previousDefaultBackendClass. + (MCPOpenTelemetryObservabilityBackend classVariableNamed: #LocalSpansEnabled) value: previousLocalSpans. backend := nil. self restoreEnvironment. super tearDown diff --git a/src/MCP-OpenTelemetry-UI/MCP.extension.st b/src/MCP-OpenTelemetry-UI/MCP.extension.st index 05517748..da50000d 100644 --- a/src/MCP-OpenTelemetry-UI/MCP.extension.st +++ b/src/MCP-OpenTelemetry-UI/MCP.extension.st @@ -3,6 +3,6 @@ Extension { #name : 'MCP' } { #category : '*MCP-OpenTelemetry-UI' } MCP >> inspectionCallGraph: aBuilder [ - + ^ MCPCallGraphPresenter on: self ] diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st index 5189564f..6629b5c1 100644 --- a/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st @@ -1,12 +1,21 @@ " -Draws a MCPOcelFlowGraph on a Roassal canvas: a box per tool, from the left in the order the calls went, and an arrow per directly-follows edge, thicker the more cases it has. A tool that follows itself shows how many times in its box rather than as an arrow, and a tool with failed calls has a red border. Hovering a box or an arrow says its numbers. +Draws a MCPOcelFlowGraph on a Roassal canvas: a box per tool, from the left in the order the calls went, and an arrow per directly-follows edge, thicker the more cases it has. A tool that follows itself shows how many times in its box rather than as an arrow, and a tool with failed calls has a red border. It is interactive: boxes can be dragged, hovering a box or an arrow lights it with what it is connected to and dims the rest, and hovering says its numbers; clicking a box or an arrow selects it and tells whoever listens (onActivityClicked:, onEdgeClicked:), which may select it in its own way, and selectActivity: and selectEdgeFrom:to: select from the outside without telling. Positions the user dragged boxes to can be handed to the next drawing (initialPositions:) so that a redraw does not undo them. " Class { #name : 'MCPCallGraphDrawing', #superclass : 'Object', #instVars : [ 'flowGraph', - 'nodes' + 'nodes', + 'canvas', + 'lines', + 'hoveredActivity', + 'hoveredEdge', + 'selectedActivity', + 'selectedEdge', + 'initialPositions', + 'onActivityClicked', + 'onEdgeClicked' ], #category : 'MCP-OpenTelemetry-UI', #package : 'MCP-OpenTelemetry-UI' @@ -16,13 +25,116 @@ Class { MCPCallGraphDrawing class >> drawFlowGraph: aFlowGraph on: aCanvas [ "Replaces what aCanvas shows with the graph." - aCanvas shapes copy do: [ :shape | shape remove ]. ^ self new flowGraph: aFlowGraph; drawOn: aCanvas; yourself ] +{ #category : 'interaction' } +MCPCallGraphDrawing >> addInteractions [ + + nodes do: [ :node | + | activity | + activity := node model. + node @ RSDraggable. + node + when: RSMouseEnter do: [ :event | + hoveredActivity := activity. + self applyStyles ] + for: self; + when: RSMouseLeave do: [ :event | + hoveredActivity := nil. + self applyStyles ] + for: self; + when: RSMouseClick do: [ :event | self clickActivity: activity ] for: self ]. + lines keysAndValuesDo: [ :key :line | + line + when: RSMouseEnter do: [ :event | + hoveredEdge := key. + self applyStyles ] + for: self; + when: RSMouseLeave do: [ :event | + hoveredEdge := nil. + self applyStyles ] + for: self; + when: RSMouseClick do: [ :event | self clickEdge: key ] for: self ] +] + +{ #category : 'styling' } +MCPCallGraphDrawing >> applyStyles [ + "What is hovered, else what is selected, is lit with what it is connected to, and the rest is dimmed: a tool lights its arrows and the tools at their ends, an arrow its two tools." + + | focusActivity focusEdge anyFocus | + focusActivity := hoveredActivity ifNil: [ hoveredEdge ifNil: [ selectedActivity ] ifNotNil: [ nil ] ]. + focusEdge := hoveredEdge ifNil: [ hoveredActivity ifNil: [ selectedEdge ] ifNotNil: [ nil ] ]. + anyFocus := focusActivity isNotNil or: [ focusEdge isNotNil ]. + nodes do: [ :node | + | activity lit | + activity := node model. + lit := anyFocus not or: [ self isActivity: activity litBy: focusActivity edge: focusEdge ]. + node shapes first border: (self borderOf: activity lit: lit focused: activity = focusActivity) ]. + lines keysAndValuesDo: [ :key :line | + | lit | + lit := self isEdge: key litBy: focusActivity edge: focusEdge. + line color: (lit + ifTrue: [ self litColor ] + ifFalse: [ + Color gray alpha: (anyFocus + ifTrue: [ 0.25 ] + ifFalse: [ 0.8 ]) ]) ]. + canvas signalUpdate +] + +{ #category : 'styling' } +MCPCallGraphDrawing >> borderOf: anActivity lit: lit focused: focused [ + "Red for a tool with failed calls, else blue when lit and gray when not; thicker for the focused one, and faded when something else is." + + | failed color | + failed := (flowGraph errorCountOf: anActivity) > 0. + color := failed + ifTrue: [ Color red ] + ifFalse: [ + lit + ifTrue: [ self litColor ] + ifFalse: [ Color gray ] ]. + ^ RSBorder new + color: (lit + ifTrue: [ color ] + ifFalse: [ color alpha: 0.3 ]); + width: (focused + ifTrue: [ 3 ] + ifFalse: [ + failed + ifTrue: [ 2 ] + ifFalse: [ 1 ] ]); + yourself +] + +{ #category : 'interaction' } +MCPCallGraphDrawing >> clickActivity: anActivity [ + "Selects the tool, or drops the selection when it is the one selected, and tells the listener." + + selectedEdge := nil. + selectedActivity := selectedActivity = anActivity + ifTrue: [ nil ] + ifFalse: [ anActivity ]. + self applyStyles. + onActivityClicked ifNotNil: [ :block | block value: selectedActivity ] +] + +{ #category : 'interaction' } +MCPCallGraphDrawing >> clickEdge: anEdgeKey [ + "Selects the arrow, or drops the selection when it is the one selected, and tells the listener with the edge." + + selectedActivity := nil. + selectedEdge := selectedEdge = anEdgeKey + ifTrue: [ nil ] + ifFalse: [ anEdgeKey ]. + self applyStyles. + onEdgeClicked ifNotNil: [ :block | block value: (selectedEdge ifNotNil: [ :key | flowGraph edgeFrom: key key to: key value ]) ] +] + { #category : 'drawing' } MCPCallGraphDrawing >> describe: anActivity [ @@ -56,20 +168,21 @@ MCPCallGraphDrawing >> describeEdge: anEdge [ ] { #category : 'drawing' } -MCPCallGraphDrawing >> drawEdgesOn: aCanvas [ +MCPCallGraphDrawing >> drawEdges [ | arrows | + lines := Dictionary new. arrows := flowGraph edges reject: [ :edge | edge isSelfLoop ]. arrows isEmpty ifTrue: [ ^ self ]. RSLineBuilder arrowedLine - canvas: aCanvas; + canvas: canvas; withBorderAttachPoint; - color: (Color gray alpha: 0.8); shapes: nodes; useAssociations: (arrows collect: [ :edge | edge source -> edge target ] as: Array). - aCanvas edges do: [ :line | + canvas edges do: [ :line | | edge | edge := flowGraph edgeFrom: line model key to: line model value. + lines at: line model put: line. line width: 1 + (edge count log: 2); popupText: [ :each | self describeEdge: edge ] ] @@ -78,10 +191,14 @@ MCPCallGraphDrawing >> drawEdgesOn: aCanvas [ { #category : 'drawing' } MCPCallGraphDrawing >> drawOn: aCanvas [ + canvas := aCanvas. + canvas shapes copy do: [ :shape | shape remove ]. nodes := flowGraph activitiesByFirstCall collect: [ :activity | self nodeFor: activity ]. - aCanvas addAll: nodes. - self drawEdgesOn: aCanvas. - self layOutNodes + canvas addAll: nodes. + self drawEdges. + self layOutNodes. + self addInteractions. + self applyStyles ] { #category : 'accessing' } @@ -90,6 +207,31 @@ MCPCallGraphDrawing >> flowGraph: aFlowGraph [ flowGraph := aFlowGraph ] +{ #category : 'accessing' } +MCPCallGraphDrawing >> initialPositions: aDictionary [ + "Where the boxes of these tools were, as tool -> point, which a box is put back to." + + initialPositions := aDictionary +] + +{ #category : 'styling' } +MCPCallGraphDrawing >> isActivity: anActivity litBy: focusActivity edge: focusEdge [ + + focusActivity ifNotNil: [ + anActivity = focusActivity ifTrue: [ ^ true ]. + ^ lines keys anySatisfy: [ :key | + (key key = focusActivity and: [ key value = anActivity ]) or: [ key value = focusActivity and: [ key key = anActivity ] ] ] ]. + focusEdge ifNotNil: [ ^ anActivity = focusEdge key or: [ anActivity = focusEdge value ] ]. + ^ false +] + +{ #category : 'styling' } +MCPCallGraphDrawing >> isEdge: anEdgeKey litBy: focusActivity edge: focusEdge [ + + focusActivity ifNotNil: [ ^ anEdgeKey key = focusActivity or: [ anEdgeKey value = focusActivity ] ]. + ^ focusEdge = anEdgeKey +] + { #category : 'drawing' } MCPCallGraphDrawing >> labelOf: anActivity [ "The tool, and how many times it follows itself when it does." @@ -105,35 +247,34 @@ MCPCallGraphDrawing >> labelOf: anActivity [ { #category : 'layout' } MCPCallGraphDrawing >> layOutNodes [ - "A column per layer, from the left, its boxes one under the other in the order of their first call, centered on the middle." + "A column per layer, from the left, its boxes one under the other in the order of their first call, centered on the middle; but a box the user had dragged somewhere stays there." | layers columnWidth rowHeight | layers := flowGraph layers. columnWidth := (nodes inject: 0 into: [ :widest :node | widest max: node width ]) + 90. rowHeight := 60. (nodes groupedBy: [ :node | layers at: node model ]) keysAndValuesDo: [ :layer :column | - column withIndexDo: [ :node :index | node position: layer * columnWidth @ (index - 1 - (column size - 1 / 2) * rowHeight) ] ] + column withIndexDo: [ :node :index | node position: layer * columnWidth @ (index - 1 - (column size - 1 / 2) * rowHeight) ] ]. + initialPositions ifNotNil: [ + nodes do: [ :node | initialPositions at: node model ifPresent: [ :position | node position: position ] ] ] +] + +{ #category : 'styling' } +MCPCallGraphDrawing >> litColor [ + + ^ Color fromHexString: '2B6FDB' ] { #category : 'drawing' } MCPCallGraphDrawing >> nodeFor: anActivity [ - | label box errors | - errors := flowGraph errorCountOf: anActivity. + | label box | label := RSLabel new text: (self labelOf: anActivity); yourself. box := RSBox new extent: label textWidth + 20 @ 28; color: Color white; - border: (RSBorder new - color: (errors > 0 - ifTrue: [ Color red ] - ifFalse: [ Color gray ]); - width: (errors > 0 - ifTrue: [ 2 ] - ifFalse: [ 1 ]); - yourself); cornerRadius: 6; yourself. ^ RSComposite new @@ -144,3 +285,49 @@ MCPCallGraphDrawing >> nodeFor: anActivity [ popupText: [ :activity | self describe: activity ]; yourself ] + +{ #category : 'accessing' } +MCPCallGraphDrawing >> nodePositions [ + "Where the box of each tool is now, which a drag may have changed." + + | positions | + positions := Dictionary new. + nodes ifNotNil: [ nodes do: [ :node | positions at: node model put: node position ] ]. + ^ positions +] + +{ #category : 'accessing' } +MCPCallGraphDrawing >> onActivityClicked: aBlock [ + "Evaluated with the tool whose box was clicked." + + onActivityClicked := aBlock +] + +{ #category : 'accessing' } +MCPCallGraphDrawing >> onEdgeClicked: aBlock [ + "Evaluated with the edge whose arrow was clicked." + + onEdgeClicked := aBlock +] + +{ #category : 'interaction' } +MCPCallGraphDrawing >> selectActivity: anActivity [ + "Selects the tool from the outside, nil to drop the selection, without telling the listener." + + selectedEdge := nil. + selectedActivity := anActivity. + self applyStyles +] + +{ #category : 'interaction' } +MCPCallGraphDrawing >> selectEdge: anEdge [ + "Selects the arrow of an edge from the outside, nil to drop the selection, without telling the listener. A tool that follows itself has no arrow: its box is selected instead." + + selectedActivity := nil. + selectedEdge := nil. + anEdge ifNotNil: [ + anEdge isSelfLoop + ifTrue: [ selectedActivity := anEdge source ] + ifFalse: [ selectedEdge := anEdge source -> anEdge target ] ]. + self applyStyles +] diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st index 842b006c..3e847746 100644 --- a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st @@ -15,12 +15,33 @@ Class { 'edgesLabel', 'edgesTable', 'flowGraph', - 'graphPresenter' + 'graphPresenter', + 'drawing', + 'isSyncingSelection' ], #category : 'MCP-OpenTelemetry-UI', #package : 'MCP-OpenTelemetry-UI' } +{ #category : 'actions' } +MCPCallGraphPresenter >> activityClickedInGraph: anActivity [ + "A click on a box selects the tool in its table, and none of the arrows'; clicking the selected one again selects nothing." + + self syncingSelectionDo: [ + edgesTable unselectAll. + anActivity ifNil: [ activitiesTable unselectAll ] ifNotNil: [ activitiesTable selectItem: anActivity ] ] +] + +{ #category : 'actions' } +MCPCallGraphPresenter >> activitySelectedInTable [ + "Selecting a tool in its table lights its box in the graph, and drops the selection of an arrow." + + isSyncingSelection == true ifTrue: [ ^ self ]. + self syncingSelectionDo: [ + activitiesTable selectedItem ifNotNil: [ edgesTable unselectAll ]. + drawing ifNotNil: [ :each | each selectActivity: activitiesTable selectedItem ] ] +] + { #category : 'actions' } MCPCallGraphPresenter >> clearSpans [ @@ -34,7 +55,9 @@ MCPCallGraphPresenter >> connectPresenters [ localSpansCheckBox whenChangedDo: [ :enabled | self localSpansChangedTo: enabled ]. objectTypeDropList whenSelectedItemChangedDo: [ :type | self refreshView ]. refreshButton action: [ self refreshView ]. - clearButton action: [ self clearSpans ] + clearButton action: [ self clearSpans ]. + activitiesTable whenSelectionChangedDo: [ :selection | self activitySelectedInTable ]. + edgesTable whenSelectionChangedDo: [ :selection | self edgeSelectedInTable ] ] { #category : 'layout' } @@ -71,15 +94,40 @@ MCPCallGraphPresenter >> defaultLayout [ { #category : 'updating' } MCPCallGraphPresenter >> drawGraph [ - "Draws the graph of the last refresh. Setting the script redraws, so a new block each time; the canvas gets its controller, for zoom and drag, once." + "Draws the graph of the last refresh. Setting the script redraws, so a new block each time; the canvas gets its controller, for zoom and drag, once. The boxes the user dragged keep their places." - | graph | + | graph positions | graph := flowGraph. + positions := drawing ifNotNil: [ :previous | previous nodePositions ]. graphPresenter script: [ :canvas | - MCPCallGraphDrawing drawFlowGraph: graph on: canvas. + drawing := MCPCallGraphDrawing new + flowGraph: graph; + initialPositions: positions; + onActivityClicked: [ :activity | self activityClickedInGraph: activity ]; + onEdgeClicked: [ :edge | self edgeClickedInGraph: edge ]; + drawOn: canvas; + yourself. canvas controllerInteraction ifNil: [ canvas @ RSCanvasController ] ] ] +{ #category : 'actions' } +MCPCallGraphPresenter >> edgeClickedInGraph: anEdge [ + + self syncingSelectionDo: [ + activitiesTable unselectAll. + anEdge ifNil: [ edgesTable unselectAll ] ifNotNil: [ edgesTable selectItem: anEdge ] ] +] + +{ #category : 'actions' } +MCPCallGraphPresenter >> edgeSelectedInTable [ + "Selecting an edge in its table lights its arrow in the graph, and drops the selection of a tool." + + isSyncingSelection == true ifTrue: [ ^ self ]. + self syncingSelectionDo: [ + edgesTable selectedItem ifNotNil: [ activitiesTable unselectAll ]. + drawing ifNotNil: [ :each | each selectEdge: edgesTable selectedItem ] ] +] + { #category : 'initialization' } MCPCallGraphPresenter >> initializePresenters [ @@ -136,10 +184,10 @@ MCPCallGraphPresenter >> localSpansChangedTo: enabled [ | mcp | mcp := self model ifNil: [ ^ self ]. - MCPOpenTelemetryObservabilityBackend isLocalSpansEnabled = enabled ifTrue: [ ^ self ]. (enabled and: [ (mcp observability isKindOf: MCPOpenTelemetryObservabilityBackend) not ]) ifTrue: [ mcp useOpenTelemetryObservability ]. - MCPOpenTelemetryObservabilityBackend useLocalSpans: enabled. + MCPOpenTelemetryObservabilityBackend isLocalSpansEnabled = enabled ifFalse: [ + MCPOpenTelemetryObservabilityBackend useLocalSpans: enabled ]. self refreshView ] @@ -221,3 +269,13 @@ MCPCallGraphPresenter >> statusFor: mcp enabled: enabled events: eventCount [ (mcp observability isKindOf: MCPOpenTelemetryObservabilityBackend) ifFalse: [ stream nextPutAll: ' - this server does not record through OpenTelemetry' ] ] ] ] + +{ #category : 'actions' } +MCPCallGraphPresenter >> syncingSelectionDo: aBlock [ + "Selecting in one place selects in the other, which must not select back." + + | wasSyncing | + wasSyncing := isSyncingSelection == true. + isSyncingSelection := true. + aBlock ensure: [ isSyncingSelection := wasSyncing ] +] From 5f57d69809642e4ddf3ad56a9bd58967854469af Mon Sep 17 00:00:00 2001 From: alkalinan Date: Tue, 24 Nov 2026 13:34:50 +0100 Subject: [PATCH 07/11] Add an auto-refresh toggle to the OCEL tab --- .../MCPCallGraphPresenter.class.st | 129 +++++++++++++++++- 1 file changed, 122 insertions(+), 7 deletions(-) diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st index 3e847746..6559ac51 100644 --- a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st @@ -17,7 +17,10 @@ Class { 'flowGraph', 'graphPresenter', 'drawing', - 'isSyncingSelection' + 'isSyncingSelection', + 'autoRefreshCheckBox', + 'autoRefreshProcess', + 'lastSignature' ], #category : 'MCP-OpenTelemetry-UI', #package : 'MCP-OpenTelemetry-UI' @@ -42,6 +45,31 @@ MCPCallGraphPresenter >> activitySelectedInTable [ drawing ifNotNil: [ :each | each selectActivity: activitiesTable selectedItem ] ] ] +{ #category : 'auto-refresh' } +MCPCallGraphPresenter >> autoRefreshChangedTo: enabled [ + + enabled + ifTrue: [ + self refreshViewForcing: false. + self startAutoRefresh ] + ifFalse: [ self stopAutoRefreshProcess ] +] + +{ #category : 'auto-refresh' } +MCPCallGraphPresenter >> autoRefreshIntervalSeconds [ + + ^ 2 +] + +{ #category : 'auto-refresh' } +MCPCallGraphPresenter >> autoRefreshLoop [ + + [ + [ self shouldAutoRefresh ] whileTrue: [ + (Delay forSeconds: self autoRefreshIntervalSeconds) wait. + self shouldAutoRefresh ifTrue: [ self defer: [ self refreshViewForcing: false ] ] ] ] ensure: [ autoRefreshProcess := nil ] +] + { #category : 'actions' } MCPCallGraphPresenter >> clearSpans [ @@ -53,6 +81,7 @@ MCPCallGraphPresenter >> clearSpans [ MCPCallGraphPresenter >> connectPresenters [ localSpansCheckBox whenChangedDo: [ :enabled | self localSpansChangedTo: enabled ]. + autoRefreshCheckBox whenChangedDo: [ :enabled | self autoRefreshChangedTo: enabled ]. objectTypeDropList whenSelectedItemChangedDo: [ :type | self refreshView ]. refreshButton action: [ self refreshView ]. clearButton action: [ self clearSpans ]. @@ -67,6 +96,7 @@ MCPCallGraphPresenter >> controlsLayout [ spacing: 8; vAlignCenter; add: localSpansCheckBox expand: false; + add: autoRefreshCheckBox expand: false; add: objectTypeDropList expand: false; add: refreshButton expand: false; add: clearButton expand: false; @@ -132,6 +162,7 @@ MCPCallGraphPresenter >> edgeSelectedInTable [ MCPCallGraphPresenter >> initializePresenters [ localSpansCheckBox := self newCheckBox. + autoRefreshCheckBox := self newCheckBox. objectTypeDropList := self newDropList. refreshButton := self newButton. clearButton := self newButton. @@ -143,6 +174,7 @@ MCPCallGraphPresenter >> initializePresenters [ edgesTable := self newTable. localSpansCheckBox label: 'Keep spans (no export)'. + autoRefreshCheckBox label: 'Auto-refresh'. objectTypeDropList items: MCPOcelLog new objectTypes; display: [ :type | 'Object: ' , type ]. @@ -178,6 +210,25 @@ MCPCallGraphPresenter >> initializeTables [ beResizable ] +{ #category : 'initialization' } +MCPCallGraphPresenter >> initializeWindow: aWindowPresenter [ + + super initializeWindow: aWindowPresenter. + aWindowPresenter whenClosedDo: [ self stopAutoRefresh ] +] + +{ #category : 'auto-refresh' } +MCPCallGraphPresenter >> isAutoRefreshEnabled [ + + ^ autoRefreshCheckBox state +] + +{ #category : 'auto-refresh' } +MCPCallGraphPresenter >> isAutoRefreshProcessRunning [ + + ^ autoRefreshProcess notNil and: [ autoRefreshProcess isTerminated not ] +] + { #category : 'actions' } MCPCallGraphPresenter >> localSpansChangedTo: enabled [ "The spans are made by the image's OpenTelemetry providers, which are global, so this turns them on for every server of the image; this one is switched to the OpenTelemetry backend, which makes them, when it records through another." @@ -199,20 +250,57 @@ MCPCallGraphPresenter >> modelChanged [ { #category : 'updating' } MCPCallGraphPresenter >> refreshView [ + "Brings the whole view up to date, whatever changed." - | mcp enabled log type | + self refreshViewForcing: true +] + +{ #category : 'updating' } +MCPCallGraphPresenter >> refreshViewForcing: aBoolean [ + "Rebuilds the view from the span store. Unforced, as the auto-refresh does, it does nothing when the spans, the object type and the switch are those of the last build, so the selection and the hover are not lost every few seconds for nothing." + + | mcp enabled snapshots type signature log selectedActivity selectedEdge | mcp := self model ifNil: [ ^ self ]. enabled := MCPOpenTelemetryObservabilityBackend isLocalSpansEnabled. - localSpansCheckBox state: enabled. - log := MCPOcelLog fromSpanSnapshots: MCPOpenTelemetryObservabilityBackend localSpanStore snapshots. + snapshots := MCPOpenTelemetryObservabilityBackend localSpanStore snapshots. type := objectTypeDropList selectedItem ifNil: [ 'tool' ]. + signature := { + snapshots size. + (snapshots ifNotEmpty: [ snapshots last spanId ]). + type. + enabled }. + (aBoolean not and: [ signature = lastSignature ]) ifTrue: [ ^ self ]. + lastSignature := signature. + selectedActivity := activitiesTable selectedItem. + selectedEdge := edgesTable selectedItem. + localSpansCheckBox state: enabled. + log := MCPOcelLog fromSpanSnapshots: snapshots. flowGraph := log flowGraphOfType: type. statusLabel label: (self statusFor: mcp enabled: enabled events: log events size). activitiesLabel label: (self sectionLabelFor: 'Tools' count: flowGraph activities size type: type). - activitiesTable items: flowGraph activities. edgesLabel label: (self sectionLabelFor: 'Directly follows' count: flowGraph edges size type: type). - edgesTable items: flowGraph edges asArray. - self drawGraph + self syncingSelectionDo: [ + activitiesTable items: flowGraph activities. + edgesTable items: flowGraph edges asArray ]. + self drawGraph. + self restoreSelectionOfActivity: selectedActivity edge: selectedEdge +] + +{ #category : 'updating' } +MCPCallGraphPresenter >> restoreSelectionOfActivity: anActivity edge: anEdge [ + "A rebuild makes new objects: what was selected is found again by name, and shown in the tables and in the new drawing." + + | edge | + self syncingSelectionDo: [ + (anActivity notNil and: [ flowGraph activities includes: anActivity ]) + ifTrue: [ + activitiesTable selectItem: anActivity. + drawing ifNotNil: [ :each | each selectActivity: anActivity ] ] + ifFalse: [ + edge := anEdge ifNotNil: [ flowGraph edgeFrom: anEdge source to: anEdge target ]. + edge ifNotNil: [ + edgesTable selectItem: edge. + drawing ifNotNil: [ :each | each selectEdge: edge ] ] ] ] ] { #category : 'updating' } @@ -253,6 +341,19 @@ MCPCallGraphPresenter >> sectionsLayout [ yourself ] +{ #category : 'auto-refresh' } +MCPCallGraphPresenter >> shouldAutoRefresh [ + + ^ self isAutoRefreshEnabled and: [ self isDisplayed ] +] + +{ #category : 'auto-refresh' } +MCPCallGraphPresenter >> startAutoRefresh [ + + self isAutoRefreshProcessRunning ifTrue: [ ^ self ]. + autoRefreshProcess := [ self autoRefreshLoop ] forkAt: Processor userBackgroundPriority named: 'MCP OCEL auto-refresh' +] + { #category : 'updating' } MCPCallGraphPresenter >> statusFor: mcp enabled: enabled events: eventCount [ @@ -270,6 +371,20 @@ MCPCallGraphPresenter >> statusFor: mcp enabled: enabled events: eventCount [ stream nextPutAll: ' - this server does not record through OpenTelemetry' ] ] ] ] +{ #category : 'auto-refresh' } +MCPCallGraphPresenter >> stopAutoRefresh [ + "The window is closing: nothing is left to refresh." + + self stopAutoRefreshProcess +] + +{ #category : 'auto-refresh' } +MCPCallGraphPresenter >> stopAutoRefreshProcess [ + + autoRefreshProcess ifNotNil: [ :process | process terminate ]. + autoRefreshProcess := nil +] + { #category : 'actions' } MCPCallGraphPresenter >> syncingSelectionDo: aBlock [ "Selecting in one place selects in the other, which must not select back." From c3c2920475de53760b6270f0f933e662008a0c95 Mon Sep 17 00:00:00 2001 From: alkalinan Date: Tue, 24 Nov 2026 13:38:38 +0100 Subject: [PATCH 08/11] Show the dashboard tool icons in the OCEL graph --- .../MCPCallGraphDrawing.class.st | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st index 6629b5c1..5660610b 100644 --- a/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st @@ -207,6 +207,19 @@ MCPCallGraphDrawing >> flowGraph: aFlowGraph [ flowGraph := aFlowGraph ] +{ #category : 'drawing' } +MCPCallGraphDrawing >> iconFormFor: anActivity [ + "The icon the dashboard shows for the tool of this name." + + ^ ((MCPToolIconSpec forToolName: anActivity) formUsing: MCPStructureIcon) scaledIntoFormOfSize: self iconSize +] + +{ #category : 'drawing' } +MCPCallGraphDrawing >> iconSize [ + + ^ 16 +] + { #category : 'accessing' } MCPCallGraphDrawing >> initialPositions: aDictionary [ "Where the boxes of these tools were, as tool -> point, which a box is put back to." @@ -267,20 +280,30 @@ MCPCallGraphDrawing >> litColor [ { #category : 'drawing' } MCPCallGraphDrawing >> nodeFor: anActivity [ + "A box with the icon of the tool, as in the dashboard, then its name." - | label box | + | label box icon gap padding width | + gap := 6. + padding := 10. label := RSLabel new text: (self labelOf: anActivity); yourself. + icon := RSBitmap new + form: (self iconFormFor: anActivity); + yourself. + width := padding + self iconSize + gap + label textWidth + padding. box := RSBox new - extent: label textWidth + 20 @ 28; + extent: width @ 28; color: Color white; cornerRadius: 6; yourself. + icon translateTo: padding - (width / 2) + (self iconSize / 2) @ 0. + label translateTo: padding + self iconSize + gap - (width / 2) + (label textWidth / 2) @ 0. ^ RSComposite new model: anActivity; shapes: { box. + icon. label }; popupText: [ :activity | self describe: activity ]; yourself From c4c3f8ffd81e25c29e9eed306159d460cab16499 Mon Sep 17 00:00:00 2001 From: alkalinan Date: Tue, 24 Nov 2026 13:41:17 +0100 Subject: [PATCH 09/11] Scale OCEL arrow thickness with case count and add a legend --- .../MCPCallGraphDrawing.class.st | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st index 5660610b..a5334f03 100644 --- a/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st @@ -184,10 +184,45 @@ MCPCallGraphDrawing >> drawEdges [ edge := flowGraph edgeFrom: line model key to: line model value. lines at: line model put: line. line - width: 1 + (edge count log: 2); + width: (self widthOfCount: edge count); popupText: [ :each | self describeEdge: edge ] ] ] +{ #category : 'drawing' } +MCPCallGraphDrawing >> drawLegend [ + "A fixed key at the top right of the canvas: how thick an arrow is for how many cases." + + | legend | + legend := RSLegend new. + legend container: canvas. + legend title: 'Directly follows'. + { + 1. + 10. + 25. + self maxCountForWidth } do: [ :count | + legend + text: (count = self maxCountForWidth + ifTrue: [ count printString , '+ cases' ] + ifFalse: [ + count printString , (count = 1 + ifTrue: [ ' case' ] + ifFalse: [ ' cases' ]) ]) + withShape: (RSBox new + width: 28; + height: (self widthOfCount: count); + color: Color gray; + yourself) ]. + legend legendDo: [ :shape | + shape + withBorder; + padding: 8 ]. + legend location + right; + top. + legend build +] + { #category : 'drawing' } MCPCallGraphDrawing >> drawOn: aCanvas [ @@ -198,6 +233,7 @@ MCPCallGraphDrawing >> drawOn: aCanvas [ self drawEdges. self layOutNodes. self addInteractions. + self drawLegend. self applyStyles ] @@ -278,6 +314,13 @@ MCPCallGraphDrawing >> litColor [ ^ Color fromHexString: '2B6FDB' ] +{ #category : 'drawing' } +MCPCallGraphDrawing >> maxCountForWidth [ + "From this many cases on, an arrow is as thick as it gets." + + ^ 50 +] + { #category : 'drawing' } MCPCallGraphDrawing >> nodeFor: anActivity [ "A box with the icon of the tool, as in the dashboard, then its name." @@ -354,3 +397,10 @@ MCPCallGraphDrawing >> selectEdge: anEdge [ ifFalse: [ selectedEdge := anEdge source -> anEdge target ] ]. self applyStyles ] + +{ #category : 'drawing' } +MCPCallGraphDrawing >> widthOfCount: aCount [ + "From 1 pixel for a single case, growing in step with the count, to 9 pixels at the maximum and above." + + ^ 1 + (8 * ((aCount min: self maxCountForWidth) - 1) / (self maxCountForWidth - 1)) +] From 9a66ba3fd97b09606592c09715ca0171a54afd82 Mon Sep 17 00:00:00 2001 From: alkalinan Date: Tue, 24 Nov 2026 14:31:47 +0100 Subject: [PATCH 10/11] Export and import the OCEL spans as OCEL 2.0 JSON Open the OCEL tab on the session object type --- .../MCPOcelSpanArchiveTest.class.st | 135 +++++++++++++++ .../MCPCallGraphPresenter.class.st | 134 ++++++++++++++- .../MCPOcel2Archive.class.st | 162 ++++++++++++++++++ .../MCPOcelRecordedSpan.class.st | 76 ++++++++ .../MCPOcelRecordedSpanContext.class.st | 24 +++ .../MCPOcelSpanArchive.class.st | 126 ++++++++++++++ .../MCPOpenTelemetryLocalSpanStore.class.st | 13 ++ 7 files changed, 667 insertions(+), 3 deletions(-) create mode 100644 src/MCP-OpenTelemetry-Tests/MCPOcelSpanArchiveTest.class.st create mode 100644 src/MCP-OpenTelemetry/MCPOcel2Archive.class.st create mode 100644 src/MCP-OpenTelemetry/MCPOcelRecordedSpan.class.st create mode 100644 src/MCP-OpenTelemetry/MCPOcelRecordedSpanContext.class.st create mode 100644 src/MCP-OpenTelemetry/MCPOcelSpanArchive.class.st diff --git a/src/MCP-OpenTelemetry-Tests/MCPOcelSpanArchiveTest.class.st b/src/MCP-OpenTelemetry-Tests/MCPOcelSpanArchiveTest.class.st new file mode 100644 index 00000000..50b84c8d --- /dev/null +++ b/src/MCP-OpenTelemetry-Tests/MCPOcelSpanArchiveTest.class.st @@ -0,0 +1,135 @@ +" +The file the spans of the call graph are saved in and read back from. +" +Class { + #name : 'MCPOcelSpanArchiveTest', + #superclass : 'TestCase', + #category : 'MCP-OpenTelemetry-Tests', + #package : 'MCP-OpenTelemetry-Tests' +} + +{ #category : 'fixtures' } +MCPOcelSpanArchiveTest >> someSpans [ + + ^ { + (MCPOcelTestSpan + tool: 'evaluate' + id: 'a1' + parent: nil + startMillisecond: 0 + durationMilliseconds: 40 + session: 's1' + failed: false). + (MCPOcelTestSpan + tool: 'class_get' + id: 'a2' + parent: 'a1' + startMillisecond: 5 + durationMilliseconds: 10 + session: 's1' + failed: true). + (MCPOcelTestSpan + tool: 'method_get' + id: 'a3' + parent: nil + startMillisecond: 100 + durationMilliseconds: 10 + session: 's2' + failed: false) } +] + +{ #category : 'tests' } +MCPOcelSpanArchiveTest >> testAFileIsWrittenAndReadBack [ + + | file spans | + file := FileReference newTempFilePrefix: 'ocel-' suffix: '.json'. + [ + MCPOcelSpanArchive write: self someSpans to: file. + spans := MCPOcelSpanArchive readSpansFrom: file ] ensure: [ file ensureDelete ]. + self assert: (spans collect: #spanId) asArray equals: #( 'a1' 'a2' 'a3' ). + self assert: (spans collect: #status) asArray equals: { + OTSpan unset. + OTSpan error. + OTSpan unset } +] + +{ #category : 'tests' } +MCPOcelSpanArchiveTest >> testAFileThatIsNotOfSpansIsRefused [ + + self should: [ MCPOcelSpanArchive spansFromJson: '{"hello": 1}' ] raise: Error. + self should: [ MCPOcelSpanArchive spansFromJson: 'not json at all' ] raise: Error +] + +{ #category : 'tests' } +MCPOcelSpanArchiveTest >> testAnOcel2FileOfAnotherToolGivesItsEventTypesAsTools [ + + | spans | + spans := MCPOcelSpanArchive spansFromJson: '{ + "objectTypes": [{"name": "session", "attributes": []}], + "eventTypes": [{"name": "search", "attributes": []}], + "objects": [{"id": "s-9", "type": "session", "attributes": []}], + "events": [{"id": "e1", "type": "search", "time": "2026-03-01T10:00:00Z", + "attributes": [], "relationships": [{"objectId": "s-9", "qualifier": "in"}]}]}'. + self assert: spans size equals: 1. + self assert: (MCPOcelLog fromSpanSnapshots: spans) events first activity equals: 'search'. + self assert: ((MCPOcelLog fromSpanSnapshots: spans) objectIdsOfType: 'session') asArray equals: #( 's-9' ) +] + +{ #category : 'tests' } +MCPOcelSpanArchiveTest >> testOcel2HasTheFourSectionsOfTheFormat [ + + | root | + root := STONJSON fromString: (MCPOcel2Archive jsonFor: (MCPOcelLog fromSpanSnapshots: self someSpans)). + self assert: root keys asSortedCollection asArray equals: #( 'eventTypes' 'events' 'objectTypes' 'objects' ). + self assert: (root at: 'events') size equals: 3. + self + assert: ((root at: 'objects') collect: [ :each | each at: 'id' ]) asSet + equals: #( 'tool:evaluate' 'tool:class_get' 'tool:method_get' 'session:s1' 'session:s2' ) asSet +] + +{ #category : 'tests' } +MCPOcelSpanArchiveTest >> testOcel2ReadBackGivesTheSameLog [ + + | before after json | + before := MCPOcelLog fromSpanSnapshots: self someSpans. + json := MCPOcel2Archive jsonFor: before. + after := MCPOcelLog fromSpanSnapshots: (MCPOcelSpanArchive spansFromJson: json). + self assert: (after events collect: #id) equals: (before events collect: #id). + self assert: (after events collect: #activity) equals: (before events collect: #activity). + self assert: (after events collect: #startedAt) equals: (before events collect: #startedAt). + self assert: (after events collect: #finishedAt) equals: (before events collect: #finishedAt). + self assert: (after events collect: #isError) equals: (before events collect: #isError). + self assert: (after events collect: #parentId) equals: (before events collect: #parentId). + before objectTypes do: [ :type | + self + assert: (after objectIdsOfType: type) asSortedCollection asArray + equals: (before objectIdsOfType: type) asSortedCollection asArray ] +] + +{ #category : 'tests' } +MCPOcelSpanArchiveTest >> testSpansReadBackGiveTheSameLog [ + + | before after | + before := MCPOcelLog fromSpanSnapshots: self someSpans. + after := MCPOcelLog fromSpanSnapshots: (MCPOcelSpanArchive spansFromJson: (MCPOcelSpanArchive jsonFor: self someSpans)). + self assert: (after events collect: #id) equals: (before events collect: #id). + self assert: (after events collect: #activity) equals: (before events collect: #activity). + self assert: (after events collect: #startedAt) equals: (before events collect: #startedAt). + self assert: (after events collect: #isError) equals: (before events collect: #isError). + self assert: (after events collect: #parentId) equals: (before events collect: #parentId). + MCPOcelLog new objectTypes do: [ :type | + self + assert: (after objectIdsOfType: type) asSortedCollection asArray + equals: (before objectIdsOfType: type) asSortedCollection asArray ] +] + +{ #category : 'tests' } +MCPOcelSpanArchiveTest >> testTheStoreAddsOnlyTheSpansItDoesNotHold [ + + | store spans | + store := MCPOpenTelemetryLocalSpanStore new. + spans := MCPOcelSpanArchive spansFromJson: (MCPOcelSpanArchive jsonFor: self someSpans). + self assert: (store addAllNew: spans) equals: 3. + self assert: (store addAllNew: spans) equals: 0. + self assert: store size equals: 3 +] diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st index 6559ac51..5fe4e756 100644 --- a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st @@ -20,7 +20,9 @@ Class { 'isSyncingSelection', 'autoRefreshCheckBox', 'autoRefreshProcess', - 'lastSignature' + 'lastSignature', + 'exportButton', + 'importButton' ], #category : 'MCP-OpenTelemetry-UI', #package : 'MCP-OpenTelemetry-UI' @@ -85,6 +87,8 @@ MCPCallGraphPresenter >> connectPresenters [ objectTypeDropList whenSelectedItemChangedDo: [ :type | self refreshView ]. refreshButton action: [ self refreshView ]. clearButton action: [ self clearSpans ]. + exportButton action: [ self exportSpans ]. + importButton action: [ self importSpans ]. activitiesTable whenSelectionChangedDo: [ :selection | self activitySelectedInTable ]. edgesTable whenSelectionChangedDo: [ :selection | self edgeSelectedInTable ] ] @@ -100,6 +104,8 @@ MCPCallGraphPresenter >> controlsLayout [ add: objectTypeDropList expand: false; add: refreshButton expand: false; add: clearButton expand: false; + add: exportButton expand: false; + add: importButton expand: false; yourself ] @@ -122,6 +128,13 @@ MCPCallGraphPresenter >> defaultLayout [ yourself ] +{ #category : 'updating' } +MCPCallGraphPresenter >> defaultObjectType [ + "The object type the graph follows until another is picked." + + ^ 'session' +] + { #category : 'updating' } MCPCallGraphPresenter >> drawGraph [ "Draws the graph of the last refresh. Setting the script redraws, so a new block each time; the canvas gets its controller, for zoom and drag, once. The boxes the user dragged keep their places." @@ -158,6 +171,68 @@ MCPCallGraphPresenter >> edgeSelectedInTable [ drawing ifNotNil: [ :each | each selectEdge: edgesTable selectedItem ] ] ] +{ #category : 'actions' } +MCPCallGraphPresenter >> exportSpans [ + "Saves the kept spans in the file and the format the user picks: the spans as they are, or the OCEL 2.0 log." + + | spans dialog | + spans := MCPOpenTelemetryObservabilityBackend localSpanStore snapshots. + spans ifEmpty: [ ^ self inform: 'No spans kept: nothing to export.' ]. + dialog := StSaveFilePresenter new. + dialog + title: 'Export spans'; + defaultFolder: FileLocator documents; + nameText: 'mcp-spans-' , Date today yyyymmdd , '.json'; + okAction: [ :file | self exportSpans: spans to: file asking: dialog ]. + self offerFormatsIn: dialog. + dialog openModal +] + +{ #category : 'actions' } +MCPCallGraphPresenter >> exportSpans: someSpans to: aFile asking: aFileDialog [ + + | ocel2 target | + ocel2 := self isOcel2FormatChosenIn: aFileDialog for: aFile. + target := aFile withExtension: (ocel2 + ifTrue: [ 'jsonocel' ] + ifFalse: [ 'json' ]). + [ + ocel2 + ifTrue: [ MCPOcelSpanArchive writeOcel2: someSpans to: target ] + ifFalse: [ MCPOcelSpanArchive write: someSpans to: target ]. + self inform: someSpans size printString , ' spans saved in ' , target basename , (ocel2 + ifTrue: [ ' (OCEL 2.0)' ] + ifFalse: [ '' ]) ] + on: Error + do: [ :error | self inform: 'Export failed: ' , error messageText ] +] + +{ #category : 'actions' } +MCPCallGraphPresenter >> importSpans [ + "Adds the spans of a file saved by Export, or an OCEL 2.0 file, to those kept: the content says which, those already kept are left out, and the view shows them." + + | dialog | + dialog := StOpenFilePresenter new. + dialog + title: 'Import spans'; + defaultFolder: FileLocator documents; + okAction: [ :file | self importSpansFrom: file ]. + self offerFormatsIn: dialog. + dialog openModal +] + +{ #category : 'actions' } +MCPCallGraphPresenter >> importSpansFrom: aFileReference [ + + | spans added | + spans := [ MCPOcelSpanArchive readSpansFrom: aFileReference ] + on: Error + do: [ :error | ^ self inform: 'Import failed: ' , error messageText ]. + added := MCPOpenTelemetryObservabilityBackend localSpanStore addAllNew: spans. + self refreshView. + self inform: added printString , ' of ' , spans size printString , ' spans added from ' , aFileReference basename +] + { #category : 'initialization' } MCPCallGraphPresenter >> initializePresenters [ @@ -166,6 +241,8 @@ MCPCallGraphPresenter >> initializePresenters [ objectTypeDropList := self newDropList. refreshButton := self newButton. clearButton := self newButton. + exportButton := self newButton. + importButton := self newButton. statusLabel := self newLabel. graphPresenter := self newRoassal. activitiesLabel := self newLabel. @@ -177,13 +254,22 @@ MCPCallGraphPresenter >> initializePresenters [ autoRefreshCheckBox label: 'Auto-refresh'. objectTypeDropList items: MCPOcelLog new objectTypes; - display: [ :type | 'Object: ' , type ]. + display: [ :type | 'Object: ' , type ]; + selectItem: self defaultObjectType. refreshButton label: 'Refresh'; icon: (self iconNamed: #refreshCircling). clearButton label: 'Clear'; icon: (self iconNamed: #trash). + exportButton + label: 'Export'; + icon: (self iconNamed: #smallSave); + help: 'Save the kept spans in a JSON file'. + importButton + label: 'Import'; + icon: (self iconNamed: #smallLoadProject); + help: 'Add the spans of a JSON file saved by Export'. self initializeTables ] @@ -229,6 +315,17 @@ MCPCallGraphPresenter >> isAutoRefreshProcessRunning [ ^ autoRefreshProcess notNil and: [ autoRefreshProcess isTerminated not ] ] +{ #category : 'actions' } +MCPCallGraphPresenter >> isOcel2FormatChosenIn: aFileDialog for: aFile [ + "The format picked in the drop list; when it is none of ours, the extension of the file says." + + | chosen | + chosen := aFileDialog fileNavigationSystem filtersDropList selectedItem name. + (chosen beginsWith: self ocel2FormatName) ifTrue: [ ^ true ]. + (chosen beginsWith: self spansFormatName) ifTrue: [ ^ false ]. + ^ aFile extension = 'jsonocel' +] + { #category : 'actions' } MCPCallGraphPresenter >> localSpansChangedTo: enabled [ "The spans are made by the image's OpenTelemetry providers, which are global, so this turns them on for every server of the image; this one is switched to the OpenTelemetry backend, which makes them, when it records through another." @@ -248,6 +345,22 @@ MCPCallGraphPresenter >> modelChanged [ self refreshView ] +{ #category : 'actions' } +MCPCallGraphPresenter >> ocel2FormatName [ + + ^ 'OCEL 2.0' +] + +{ #category : 'actions' } +MCPCallGraphPresenter >> offerFormatsIn: aFileDialog [ + "The formats come first in the drop list of the dialog, the spans one selected." + + | navigation | + navigation := aFileDialog fileNavigationSystem. + navigation filtersCustomization: self spansFileFilters. + navigation filtersDropList selectIndex: 1 +] + { #category : 'updating' } MCPCallGraphPresenter >> refreshView [ "Brings the whole view up to date, whatever changed." @@ -263,7 +376,7 @@ MCPCallGraphPresenter >> refreshViewForcing: aBoolean [ mcp := self model ifNil: [ ^ self ]. enabled := MCPOpenTelemetryObservabilityBackend isLocalSpansEnabled. snapshots := MCPOpenTelemetryObservabilityBackend localSpanStore snapshots. - type := objectTypeDropList selectedItem ifNil: [ 'tool' ]. + type := objectTypeDropList selectedItem ifNil: [ self defaultObjectType ]. signature := { snapshots size. (snapshots ifNotEmpty: [ snapshots last spanId ]). @@ -347,6 +460,21 @@ MCPCallGraphPresenter >> shouldAutoRefresh [ ^ self isAutoRefreshEnabled and: [ self isDisplayed ] ] +{ #category : 'actions' } +MCPCallGraphPresenter >> spansFileFilters [ + "What the file dialogs of export and import offer first: the JSON file of spans of this image, then OCEL 2.0." + + ^ { + (StCustomExtensionsFilter extensions: #( 'json' ) basename: self spansFormatName). + (StCustomExtensionsFilter extensions: #( 'jsonocel' 'json' ) basename: self ocel2FormatName) } +] + +{ #category : 'actions' } +MCPCallGraphPresenter >> spansFormatName [ + + ^ 'Spans' +] + { #category : 'auto-refresh' } MCPCallGraphPresenter >> startAutoRefresh [ diff --git a/src/MCP-OpenTelemetry/MCPOcel2Archive.class.st b/src/MCP-OpenTelemetry/MCPOcel2Archive.class.st new file mode 100644 index 00000000..6bd56dde --- /dev/null +++ b/src/MCP-OpenTelemetry/MCPOcel2Archive.class.st @@ -0,0 +1,162 @@ +" +The OCEL 2.0 JSON form of the call graph's log, the exchange format of object-centric process mining (objectTypes, eventTypes, objects, events). An event type is a tool, an object id is its type and its value joined by a colon. It writes a MCPOcelLog, and reads a file back as MCPOcelRecordedSpan: those of this archive with all they carry, those of other tools with the tool as the event type, and a session and a client from the objects of those types. +" +Class { + #name : 'MCPOcel2Archive', + #superclass : 'Object', + #category : 'MCP-OpenTelemetry', + #package : 'MCP-OpenTelemetry' +} + +{ #category : 'writing' } +MCPOcel2Archive class >> attributeNamed: aName value: aValue [ + + ^ Dictionary new + at: 'name' put: aName; + at: 'value' put: aValue; + yourself +] + +{ #category : 'writing' } +MCPOcel2Archive class >> eventEntryFor: anEvent [ + + | attributes relationships | + attributes := OrderedCollection new. + attributes add: (self attributeNamed: 'end_time' value: anEvent finishedAt printString). + attributes add: (self attributeNamed: 'status' value: (anEvent isError + ifTrue: [ 'error' ] + ifFalse: [ 'ok' ])). + anEvent dispatchPath ifNotNil: [ :path | attributes add: (self attributeNamed: 'dispatch_path' value: path) ]. + anEvent parentId ifNotNil: [ :id | attributes add: (self attributeNamed: 'parent_id' value: id) ]. + relationships := OrderedCollection new. + anEvent objects keysAndValuesDo: [ :type :ids | + ids do: [ :id | + relationships add: (Dictionary new + at: 'objectId' put: (self objectIdOf: id type: type); + at: 'qualifier' put: type; + yourself) ] ]. + ^ Dictionary new + at: 'id' put: anEvent id; + at: 'type' put: anEvent activity; + at: 'time' put: anEvent startedAt printString; + at: 'attributes' put: attributes asArray; + at: 'relationships' put: relationships asArray; + yourself +] + +{ #category : 'writing' } +MCPOcel2Archive class >> eventTypeEntryFor: anActivity [ + + ^ Dictionary new + at: 'name' put: anActivity; + at: 'attributes' put: (#( 'end_time' 'status' 'dispatch_path' 'parent_id' ) collect: [ :name | + Dictionary new + at: 'name' put: name; + at: 'type' put: (name = 'end_time' + ifTrue: [ 'time' ] + ifFalse: [ 'string' ]); + yourself ]); + yourself +] + +{ #category : 'reading' } +MCPOcel2Archive class >> isOcelRoot: aRoot [ + "What tells an OCEL 2.0 file from a file of spans: it has events and objects." + + ^ aRoot isDictionary and: [ (aRoot includesKey: 'events') and: [ aRoot includesKey: 'objects' ] ] +] + +{ #category : 'writing' } +MCPOcel2Archive class >> jsonFor: aLog [ + "The file text of this log." + + | events | + events := aLog events. + ^ STONJSON toStringPretty: (Dictionary new + at: 'objectTypes' put: (aLog objectTypes collect: [ :type | self objectTypeEntryFor: type ] as: Array); + at: 'eventTypes' + put: + ((events collect: #activity as: Set) asSortedCollection collect: [ :activity | self eventTypeEntryFor: activity ] as: Array); + at: 'objects' put: (self objectEntriesOf: aLog); + at: 'events' put: (events collect: [ :event | self eventEntryFor: event ] as: Array); + yourself) +] + +{ #category : 'writing' } +MCPOcel2Archive class >> objectEntriesOf: aLog [ + + | entries | + entries := OrderedCollection new. + aLog objectTypes do: [ :type | + (aLog objectIdsOfType: type) do: [ :id | + entries add: (Dictionary new + at: 'id' put: (self objectIdOf: id type: type); + at: 'type' put: type; + at: 'attributes' put: Array new; + at: 'relationships' put: Array new; + yourself) ] ]. + ^ entries asArray +] + +{ #category : 'writing' } +MCPOcel2Archive class >> objectIdOf: aValue type: aType [ + "An id is unique in the file whatever the type: a tool and a client could have the same name." + + ^ aType , ':' , aValue +] + +{ #category : 'writing' } +MCPOcel2Archive class >> objectTypeEntryFor: aType [ + + ^ Dictionary new + at: 'name' put: aType; + at: 'attributes' put: Array new; + yourself +] + +{ #category : 'reading' } +MCPOcel2Archive class >> spanFrom: anEvent objectTypes: typeOfObject [ + "The tool is the type of the event. A session and a client are the first objects of those types it relates to, as their value without the type this archive puts before it." + + | values attributes start | + values := Dictionary new. + (anEvent at: 'attributes' ifAbsent: [ #( ) ]) do: [ :each | values at: (each at: 'name') put: (each at: 'value') ]. + start := DateAndTime fromString: (anEvent at: 'time'). + attributes := OrderedDictionary new. + attributes at: 'gen_ai.tool.name' put: (anEvent at: 'type'). + values at: 'dispatch_path' ifPresent: [ :path | attributes at: 'pharo.mcp.dispatch_path' put: path ]. + { + ('session' -> 'session.id'). + ('client' -> 'pharo.mcp.client.name') } do: [ :each | + (self valueOfFirstObjectOfType: each key in: anEvent objectTypes: typeOfObject) ifNotNil: [ :value | + attributes at: each value put: value ] ]. + ^ MCPOcelRecordedSpan new + name: 'tools/call ' , (anEvent at: 'type') + spanId: (anEvent at: 'id') + parentSpanId: (values at: 'parent_id' ifAbsent: [ nil ]) + startTime: start + endTime: (values at: 'end_time' ifPresent: [ :end | DateAndTime fromString: end ] ifAbsent: [ start ]) + status: (MCPOcelSpanArchive statusFrom: (values at: 'status' ifAbsent: [ 'unset' ])) + attributes: attributes; + yourself +] + +{ #category : 'reading' } +MCPOcel2Archive class >> spansFromRoot: aRoot [ + "The events of an OCEL 2.0 file, as spans." + + | typeOfObject | + typeOfObject := Dictionary new. + (aRoot at: 'objects') do: [ :object | typeOfObject at: (object at: 'id') put: (object at: 'type') ]. + ^ (aRoot at: 'events') collect: [ :event | self spanFrom: event objectTypes: typeOfObject ] +] + +{ #category : 'reading' } +MCPOcel2Archive class >> valueOfFirstObjectOfType: aType in: anEvent objectTypes: typeOfObject [ + + (anEvent at: 'relationships' ifAbsent: [ #( ) ]) do: [ :relationship | + | id | + id := relationship at: 'objectId'. + (typeOfObject at: id ifAbsent: [ nil ]) = aType ifTrue: [ ^ id withoutPrefix: aType , ':' ] ]. + ^ nil +] diff --git a/src/MCP-OpenTelemetry/MCPOcelRecordedSpan.class.st b/src/MCP-OpenTelemetry/MCPOcelRecordedSpan.class.st new file mode 100644 index 00000000..2012b9b1 --- /dev/null +++ b/src/MCP-OpenTelemetry/MCPOcelRecordedSpan.class.st @@ -0,0 +1,76 @@ +" +A span read back from a file, with what a MCPOcelLog reads of a span snapshot: so that traces exported from an image can be kept, shared and loaded into the call graph of another. +" +Class { + #name : 'MCPOcelRecordedSpan', + #superclass : 'Object', + #instVars : [ + 'name', + 'spanId', + 'parentSpanId', + 'startTime', + 'endTime', + 'attributes', + 'status' + ], + #category : 'MCP-OpenTelemetry', + #package : 'MCP-OpenTelemetry' +} + +{ #category : 'accessing' } +MCPOcelRecordedSpan >> attributes [ + + ^ attributes +] + +{ #category : 'accessing' } +MCPOcelRecordedSpan >> endTime [ + + ^ endTime +] + +{ #category : 'accessing' } +MCPOcelRecordedSpan >> name [ + + ^ name +] + +{ #category : 'initialization' } +MCPOcelRecordedSpan >> name: aString spanId: anId parentSpanId: aParentId startTime: aStart endTime: anEnd status: aStatus attributes: aDictionary [ + + name := aString. + spanId := anId. + parentSpanId := aParentId. + startTime := aStart. + endTime := anEnd. + status := aStatus. + attributes := aDictionary +] + +{ #category : 'accessing' } +MCPOcelRecordedSpan >> parentSpanContext [ + "nil for a root call." + + ^ parentSpanId ifNotNil: [ :id | + MCPOcelRecordedSpanContext new + spanId: id; + yourself ] +] + +{ #category : 'accessing' } +MCPOcelRecordedSpan >> spanId [ + + ^ spanId +] + +{ #category : 'accessing' } +MCPOcelRecordedSpan >> startTime [ + + ^ startTime +] + +{ #category : 'accessing' } +MCPOcelRecordedSpan >> status [ + + ^ status +] diff --git a/src/MCP-OpenTelemetry/MCPOcelRecordedSpanContext.class.st b/src/MCP-OpenTelemetry/MCPOcelRecordedSpanContext.class.st new file mode 100644 index 00000000..3fc293b4 --- /dev/null +++ b/src/MCP-OpenTelemetry/MCPOcelRecordedSpanContext.class.st @@ -0,0 +1,24 @@ +" +The span context of the parent of a MCPOcelRecordedSpan: only its span id is known. +" +Class { + #name : 'MCPOcelRecordedSpanContext', + #superclass : 'Object', + #instVars : [ + 'spanId' + ], + #category : 'MCP-OpenTelemetry', + #package : 'MCP-OpenTelemetry' +} + +{ #category : 'accessing' } +MCPOcelRecordedSpanContext >> spanId [ + + ^ spanId +] + +{ #category : 'accessing' } +MCPOcelRecordedSpanContext >> spanId: anId [ + + spanId := anId +] diff --git a/src/MCP-OpenTelemetry/MCPOcelSpanArchive.class.st b/src/MCP-OpenTelemetry/MCPOcelSpanArchive.class.st new file mode 100644 index 00000000..5c870918 --- /dev/null +++ b/src/MCP-OpenTelemetry/MCPOcelSpanArchive.class.st @@ -0,0 +1,126 @@ +" +The JSON file format of the spans the call graph reads: { format, version, spans: [ { name, spanId, parentSpanId, startTime, endTime, status, attributes } ] }, times in ISO 8601, status one of error, ok or unset. It writes the snapshots of a span store and reads them back as MCPOcelRecordedSpan. +" +Class { + #name : 'MCPOcelSpanArchive', + #superclass : 'Object', + #category : 'MCP-OpenTelemetry', + #package : 'MCP-OpenTelemetry' +} + +{ #category : 'writing' } +MCPOcelSpanArchive class >> dictionaryFor: aSpanSnapshot [ + "What a MCPOcelLog reads of a span, and nothing else." + + | attributes | + attributes := Dictionary new. + aSpanSnapshot attributes keysAndValuesDo: [ :key :value | attributes at: key asString put: (self jsonValueOf: value) ]. + ^ Dictionary new + at: 'name' put: aSpanSnapshot name; + at: 'spanId' put: aSpanSnapshot spanId; + at: 'parentSpanId' put: (aSpanSnapshot parentSpanContext ifNotNil: [ :context | context spanId ]); + at: 'startTime' put: aSpanSnapshot startTime printString; + at: 'endTime' put: aSpanSnapshot endTime printString; + at: 'status' put: (self statusNameOf: aSpanSnapshot status); + at: 'attributes' put: attributes; + yourself +] + +{ #category : 'constants' } +MCPOcelSpanArchive class >> formatName [ + + ^ 'mcp-ocel-spans' +] + +{ #category : 'writing' } +MCPOcelSpanArchive class >> jsonFor: someSpanSnapshots [ + "The file text of these spans." + + ^ STONJSON toStringPretty: (Dictionary new + at: 'format' put: self formatName; + at: 'version' put: 1; + at: 'spans' put: (someSpanSnapshots collect: [ :snapshot | self dictionaryFor: snapshot ]) asArray; + yourself) +] + +{ #category : 'writing' } +MCPOcelSpanArchive class >> jsonValueOf: anAttributeValue [ + "Strings, numbers and booleans as they are, lists of them, and anything else as its text." + + ^ (anAttributeValue isString or: [ anAttributeValue isNumber or: [ anAttributeValue == true or: [ anAttributeValue == false ] ] ]) + ifTrue: [ anAttributeValue ] + ifFalse: [ + anAttributeValue isArray + ifTrue: [ anAttributeValue collect: [ :each | self jsonValueOf: each ] ] + ifFalse: [ anAttributeValue printString ] ] +] + +{ #category : 'files' } +MCPOcelSpanArchive class >> readSpansFrom: aFileReference [ + + ^ self spansFromJson: (aFileReference readStreamEncoded: 'utf-8' do: [ :stream | stream upToEnd ]) +] + +{ #category : 'reading' } +MCPOcelSpanArchive class >> spanFrom: aDictionary [ + + ^ MCPOcelRecordedSpan new + name: (aDictionary at: 'name') + spanId: (aDictionary at: 'spanId') + parentSpanId: (aDictionary at: 'parentSpanId' ifAbsent: [ nil ]) + startTime: (DateAndTime fromString: (aDictionary at: 'startTime')) + endTime: (DateAndTime fromString: (aDictionary at: 'endTime')) + status: (self statusFrom: (aDictionary at: 'status' ifAbsent: [ 'unset' ])) + attributes: (OrderedDictionary newFrom: (aDictionary at: 'attributes' ifAbsent: [ Dictionary new ])); + yourself +] + +{ #category : 'reading' } +MCPOcelSpanArchive class >> spansFromJson: aString [ + "The spans a file text holds, as MCPOcelRecordedSpan, whether it is of this format or OCEL 2.0. An Error says why a text is not one." + + | root | + root := [ STONJSON fromString: aString ] + on: Error + do: [ :error | self error: 'Not a JSON file: ' , error messageText ]. + (MCPOcel2Archive isOcelRoot: root) ifTrue: [ ^ MCPOcel2Archive spansFromRoot: root ]. + (root isDictionary and: [ (root at: 'format' ifAbsent: [ nil ]) = self formatName ]) ifFalse: [ + self error: 'Neither a file of spans nor an OCEL 2.0 file' ]. + ^ (root at: 'spans' ifAbsent: [ #( ) ]) collect: [ :each | self spanFrom: each ] +] + +{ #category : 'reading' } +MCPOcelSpanArchive class >> statusFrom: aName [ + + aName = 'error' ifTrue: [ ^ OTSpan error ]. + aName = 'ok' ifTrue: [ ^ OTSpan ok ]. + ^ OTSpan unset +] + +{ #category : 'writing' } +MCPOcelSpanArchive class >> statusNameOf: aStatus [ + + aStatus = OTSpan error ifTrue: [ ^ 'error' ]. + aStatus = OTSpan ok ifTrue: [ ^ 'ok' ]. + ^ 'unset' +] + +{ #category : 'files' } +MCPOcelSpanArchive class >> write: someSpanSnapshots to: aFileReference [ + "Writes the file, replacing one of that name." + + aFileReference ensureDelete. + aFileReference writeStreamEncoded: 'utf-8' do: [ :stream | stream nextPutAll: (self jsonFor: someSpanSnapshots) ]. + ^ aFileReference +] + +{ #category : 'files' } +MCPOcelSpanArchive class >> writeOcel2: someSpanSnapshots to: aFileReference [ + "The log of these spans in OCEL 2.0, replacing a file of that name." + + aFileReference ensureDelete. + aFileReference + writeStreamEncoded: 'utf-8' + do: [ :stream | stream nextPutAll: (MCPOcel2Archive jsonFor: (MCPOcelLog fromSpanSnapshots: someSpanSnapshots)) ]. + ^ aFileReference +] diff --git a/src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanStore.class.st b/src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanStore.class.st index cbd00494..af39e85d 100644 --- a/src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanStore.class.st +++ b/src/MCP-OpenTelemetry/MCPOpenTelemetryLocalSpanStore.class.st @@ -21,6 +21,19 @@ MCPOpenTelemetryLocalSpanStore >> addAll: spanSnapshots [ [ snapshots size > maxSpans ] whileTrue: [ snapshots removeFirst ] ] ] +{ #category : 'adding' } +MCPOpenTelemetryLocalSpanStore >> addAllNew: someSpans [ + "Adds those whose span id the store does not hold yet, so that loading a file twice, or one of spans the image still holds, adds nothing twice. Answers how many were added." + + | known new | + ^ mutex critical: [ + known := (snapshots collect: [ :each | each spanId ]) asSet. + new := someSpans reject: [ :each | known includes: each spanId ]. + snapshots addAll: new. + [ snapshots size > maxSpans ] whileTrue: [ snapshots removeFirst ]. + new size ] +] + { #category : 'removing' } MCPOpenTelemetryLocalSpanStore >> clear [ From 15e2418813ab3231231509e1c3e1c11069e02ef5 Mon Sep 17 00:00:00 2001 From: alkalinan Date: Tue, 24 Nov 2026 14:57:38 +0100 Subject: [PATCH 11/11] Add a layout menu to the OCEL tab, force-based by default --- .../MCPCallGraphDrawing.class.st | 132 +++++++++++++++++- .../MCPCallGraphPresenter.class.st | 27 +++- 2 files changed, 151 insertions(+), 8 deletions(-) diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st index a5334f03..c0471646 100644 --- a/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphDrawing.class.st @@ -15,12 +15,19 @@ Class { 'selectedEdge', 'initialPositions', 'onActivityClicked', - 'onEdgeClicked' + 'onEdgeClicked', + 'layoutName' ], #category : 'MCP-OpenTelemetry-UI', #package : 'MCP-OpenTelemetry-UI' } +{ #category : 'layout' } +MCPCallGraphDrawing class >> defaultLayoutName [ + + ^ self layoutNames first +] + { #category : 'drawing' } MCPCallGraphDrawing class >> drawFlowGraph: aFlowGraph on: aCanvas [ "Replaces what aCanvas shows with the graph." @@ -31,6 +38,13 @@ MCPCallGraphDrawing class >> drawFlowGraph: aFlowGraph on: aCanvas [ yourself ] +{ #category : 'layout' } +MCPCallGraphDrawing class >> layoutNames [ + "The layouts a graph can be drawn with, the default first." + + ^ #( 'Force' 'Layers' 'Circle' 'Grid' ) +] + { #category : 'interaction' } MCPCallGraphDrawing >> addInteractions [ @@ -111,6 +125,16 @@ MCPCallGraphDrawing >> borderOf: anActivity lit: lit focused: focused [ yourself ] +{ #category : 'layout' } +MCPCallGraphDrawing >> centerNodes [ + "Moves all the boxes together so that their middle is the origin." + + | sum | + nodes ifEmpty: [ ^ self ]. + sum := nodes inject: 0 @ 0 into: [ :total :node | total + node position ]. + nodes do: [ :node | node position: node position - (sum / nodes size) ] +] + { #category : 'interaction' } MCPCallGraphDrawing >> clickActivity: anActivity [ "Selects the tool, or drops the selection when it is the one selected, and tells the listener." @@ -295,19 +319,76 @@ MCPCallGraphDrawing >> labelOf: anActivity [ ] { #category : 'layout' } -MCPCallGraphDrawing >> layOutNodes [ - "A column per layer, from the left, its boxes one under the other in the order of their first call, centered on the middle; but a box the user had dragged somewhere stays there." +MCPCallGraphDrawing >> layOutByForce [ + "The arrows pull the boxes they join together, the boxes push each other apart, and everything is drawn to the middle: a tool followed by many is near them, one on its own is not far off. The same graph always gives the same drawing." + + | spread | + nodes size < 2 ifTrue: [ ^ nodes do: [ :node | node position: 0 @ 0 ] ]. + spread := (nodes inject: 0 into: [ :widest :node | widest max: node width ]) + 60. + RSForceBasedLayout new + length: spread; + charge: spread negated * 3; + gravity: 0.1; + on: nodes. + self separateOverlappingNodes. + self centerNodes +] + +{ #category : 'layout' } +MCPCallGraphDrawing >> layOutInCircle [ + "The boxes on a circle, in the order of their first call." + + nodes size < 2 ifTrue: [ ^ nodes do: [ :node | node position: 0 @ 0 ] ]. + RSCircleLayout new + initialRadius: (nodes size * 70 max: 150); + on: nodes. + self centerNodes +] + +{ #category : 'layout' } +MCPCallGraphDrawing >> layOutInGrid [ + "Rows of boxes, in the order of their first call." + + nodes size < 2 ifTrue: [ ^ nodes do: [ :node | node position: 0 @ 0 ] ]. + RSGridLayout new + gapSize: 40; + on: nodes. + self centerNodes +] + +{ #category : 'layout' } +MCPCallGraphDrawing >> layOutInLayers [ + "A column per layer, from the left, its boxes one under the other in the order of their first call, centered on the middle." | layers columnWidth rowHeight | layers := flowGraph layers. columnWidth := (nodes inject: 0 into: [ :widest :node | widest max: node width ]) + 90. rowHeight := 60. (nodes groupedBy: [ :node | layers at: node model ]) keysAndValuesDo: [ :layer :column | - column withIndexDo: [ :node :index | node position: layer * columnWidth @ (index - 1 - (column size - 1 / 2) * rowHeight) ] ]. + column withIndexDo: [ :node :index | node position: layer * columnWidth @ (index - 1 - (column size - 1 / 2) * rowHeight) ] ] +] + +{ #category : 'layout' } +MCPCallGraphDrawing >> layOutNodes [ + "The boxes put as the layout picked says; but a box the user had dragged somewhere stays there." + + | name | + name := layoutName ifNil: [ self class defaultLayoutName ]. + name = 'Layers' ifTrue: [ self layOutInLayers ]. + name = 'Force' ifTrue: [ self layOutByForce ]. + name = 'Circle' ifTrue: [ self layOutInCircle ]. + name = 'Grid' ifTrue: [ self layOutInGrid ]. initialPositions ifNotNil: [ nodes do: [ :node | initialPositions at: node model ifPresent: [ :position | node position: position ] ] ] ] +{ #category : 'accessing' } +MCPCallGraphDrawing >> layoutName: aName [ + "One of the layoutNames of the class." + + layoutName := aName +] + { #category : 'styling' } MCPCallGraphDrawing >> litColor [ @@ -398,9 +479,52 @@ MCPCallGraphDrawing >> selectEdge: anEdge [ self applyStyles ] +{ #category : 'layout' } +MCPCallGraphDrawing >> separateOverlappingNodes [ + "Boxes that touch, or come within a few pixels of each other, are pushed apart along the axis where they overlap least, until none does or the passes are spent." + + | margin | + margin := 10. + 50 timesRepeat: [ + | moved | + moved := false. + nodes doWithIndex: [ :a :i | + (nodes allButFirst: i) do: [ :b | + | ra rb overlapX overlapY | + ra := a encompassingRectangle. + rb := b encompassingRectangle. + overlapX := (ra right min: rb right) - (ra left max: rb left) + margin. + overlapY := (ra bottom min: rb bottom) - (ra top max: rb top) + margin. + (overlapX > 0 and: [ overlapY > 0 ]) ifTrue: [ + | push | + moved := true. + push := overlapX < overlapY + ifTrue: [ + overlapX / 2 * (a position x <= b position x + ifTrue: [ -1 ] + ifFalse: [ 1 ]) @ 0 ] + ifFalse: [ + 0 @ (overlapY / 2 * (a position y <= b position y + ifTrue: [ -1 ] + ifFalse: [ 1 ])) ]. + a position: a position + push. + b position: b position - push ] ] ]. + moved ifFalse: [ ^ self ] ] +] + { #category : 'drawing' } MCPCallGraphDrawing >> widthOfCount: aCount [ "From 1 pixel for a single case, growing in step with the count, to 9 pixels at the maximum and above." ^ 1 + (8 * ((aCount min: self maxCountForWidth) - 1) / (self maxCountForWidth - 1)) ] + +{ #category : 'layout' } +MCPCallGraphDrawing >> zoomToFitNodes [ + "The camera on the boxes, the legend being a corner of the view and not a part of the graph." + + | bounds | + nodes ifEmpty: [ ^ self ]. + bounds := Rectangle merging: (nodes collect: [ :node | node encompassingRectangle ]). + canvas camera zoomToFit: canvas extent rectangle: (bounds expandBy: 40) +] diff --git a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st index 5fe4e756..c95ec339 100644 --- a/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st +++ b/src/MCP-OpenTelemetry-UI/MCPCallGraphPresenter.class.st @@ -22,7 +22,8 @@ Class { 'autoRefreshProcess', 'lastSignature', 'exportButton', - 'importButton' + 'importButton', + 'layoutDropList' ], #category : 'MCP-OpenTelemetry-UI', #package : 'MCP-OpenTelemetry-UI' @@ -85,6 +86,7 @@ MCPCallGraphPresenter >> connectPresenters [ localSpansCheckBox whenChangedDo: [ :enabled | self localSpansChangedTo: enabled ]. autoRefreshCheckBox whenChangedDo: [ :enabled | self autoRefreshChangedTo: enabled ]. objectTypeDropList whenSelectedItemChangedDo: [ :type | self refreshView ]. + layoutDropList whenSelectedItemChangedDo: [ :name | self layoutChangedTo: name ]. refreshButton action: [ self refreshView ]. clearButton action: [ self clearSpans ]. exportButton action: [ self exportSpans ]. @@ -102,6 +104,7 @@ MCPCallGraphPresenter >> controlsLayout [ add: localSpansCheckBox expand: false; add: autoRefreshCheckBox expand: false; add: objectTypeDropList expand: false; + add: layoutDropList expand: false; add: refreshButton expand: false; add: clearButton expand: false; add: exportButton expand: false; @@ -137,20 +140,23 @@ MCPCallGraphPresenter >> defaultObjectType [ { #category : 'updating' } MCPCallGraphPresenter >> drawGraph [ - "Draws the graph of the last refresh. Setting the script redraws, so a new block each time; the canvas gets its controller, for zoom and drag, once. The boxes the user dragged keep their places." + "Draws the graph of the last refresh. Setting the script redraws, so a new block each time; the canvas gets its controller, for zoom and drag, once. The boxes the user dragged keep their places, and so does the zoom; but a first drawing, or a new layout, is zoomed to fit." - | graph positions | + | graph positions layoutPicked | graph := flowGraph. + layoutPicked := layoutDropList selectedItem. positions := drawing ifNotNil: [ :previous | previous nodePositions ]. graphPresenter script: [ :canvas | drawing := MCPCallGraphDrawing new flowGraph: graph; + layoutName: layoutPicked; initialPositions: positions; onActivityClicked: [ :activity | self activityClickedInGraph: activity ]; onEdgeClicked: [ :edge | self edgeClickedInGraph: edge ]; drawOn: canvas; yourself. - canvas controllerInteraction ifNil: [ canvas @ RSCanvasController ] ] + canvas controllerInteraction ifNil: [ canvas @ RSCanvasController ]. + positions ifNil: [ drawing zoomToFitNodes ] ] ] { #category : 'actions' } @@ -239,6 +245,7 @@ MCPCallGraphPresenter >> initializePresenters [ localSpansCheckBox := self newCheckBox. autoRefreshCheckBox := self newCheckBox. objectTypeDropList := self newDropList. + layoutDropList := self newDropList. refreshButton := self newButton. clearButton := self newButton. exportButton := self newButton. @@ -256,6 +263,10 @@ MCPCallGraphPresenter >> initializePresenters [ items: MCPOcelLog new objectTypes; display: [ :type | 'Object: ' , type ]; selectItem: self defaultObjectType. + layoutDropList + items: MCPCallGraphDrawing layoutNames; + display: [ :name | 'Layout: ' , name ]; + selectItem: MCPCallGraphDrawing defaultLayoutName. refreshButton label: 'Refresh'; icon: (self iconNamed: #refreshCircling). @@ -326,6 +337,14 @@ MCPCallGraphPresenter >> isOcel2FormatChosenIn: aFileDialog for: aFile [ ^ aFile extension = 'jsonocel' ] +{ #category : 'actions' } +MCPCallGraphPresenter >> layoutChangedTo: aName [ + "A new layout puts the boxes where it says: the places the user had dragged them to are forgotten." + + drawing := nil. + self refreshView +] + { #category : 'actions' } MCPCallGraphPresenter >> localSpansChangedTo: enabled [ "The spans are made by the image's OpenTelemetry providers, which are global, so this turns them on for every server of the image; this one is switched to the OpenTelemetry backend, which makes them, when it records through another."