-
Notifications
You must be signed in to change notification settings - Fork 7
New MCP tool for retrieving user audit trails from Harness #16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
abhishek-singh0710
wants to merge
13
commits into
harness:master
Choose a base branch
from
abhishek-singh0710:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
5036bab
MCP Server Audit Tool
abhishek-singh0710 5ba4a4d
Update audit.go
abhishek-singh0710 3d82f2e
Update pkg/harness.audit.go
abhishek-singh0710 0f7928d
Update audit.go
abhishek-singh0710 cc39603
Update audit.go
abhishek-singh0710 17cafba
Update audit.go
abhishek-singh0710 0112402
Update audit.go
abhishek-singh0710 d6d50ab
Update audit.go
abhishek-singh0710 5abbe91
Added tools.go file
abhishek-singh0710 40fda55
Merge branch 'harness:master' into master
abhishek-singh0710 8cb2bc3
Committing local changes
abhishek-singh0710 291fc2a
Added tools.go file
abhishek-singh0710 b7c60b1
Removed all the logging statements.
abhishek-singh0710 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
package client | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
"github.com/harness/harness-mcp/client/dto" | ||
) | ||
|
||
const ( | ||
auditPath = "gateway/audit/api/audits/list" | ||
) | ||
|
||
type AuditService struct { | ||
Client *Client | ||
} | ||
|
||
// ListUserAuditTrail fetches the audit trail. | ||
func (a *AuditService) ListUserAuditTrail(ctx context.Context, scope dto.Scope, userID string, page int, size int, startTime int64, endTime int64, opts *dto.ListAuditEventsFilter) (*dto.AuditOutput[dto.AuditListItem], error) { | ||
if opts == nil { | ||
opts = &dto.ListAuditEventsFilter{} | ||
} | ||
|
||
params := make(map[string]string) | ||
params["accountIdentifier"] = scope.AccountID | ||
params["pageIndex"] = fmt.Sprintf("%d", page) | ||
params["pageSize"] = fmt.Sprintf("%d", size) | ||
|
||
addScope(scope, params) | ||
|
||
// Required fields | ||
opts.FilterType = "Audit" | ||
opts.Principals = []dto.AuditPrincipal{{ | ||
Type: "USER", | ||
Identifier: userID, | ||
}} | ||
|
||
opts.Scopes = []dto.AuditResourceScope{{ | ||
AccountIdentifier: scope.AccountID, | ||
OrgIdentifier: scope.OrgID, | ||
ProjectIdentifier: scope.ProjectID, | ||
}} | ||
|
||
opts.StartTime = startTime // or use a date range with UnixMillis | ||
opts.EndTime = endTime | ||
|
||
resp := &dto.AuditOutput[dto.AuditListItem]{} | ||
err := a.Client.Post(ctx, auditPath, params, opts, resp) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to list the audit trail: %w", err) | ||
} | ||
|
||
return resp, nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
package dto | ||
|
||
type AuditPrincipal struct { | ||
Type string `json:"type"` | ||
Identifier string `json:"identifier"` | ||
} | ||
|
||
type AuditResourceScope struct { | ||
AccountIdentifier string `json:"accountIdentifier"` | ||
OrgIdentifier string `json:"orgIdentifier,omitempty"` | ||
ProjectIdentifier string `json:"projectIdentifier,omitempty"` | ||
} | ||
|
||
type ListAuditEventsFilter struct { | ||
Scopes []AuditResourceScope `json:"scopes,omitempty"` | ||
Principals []AuditPrincipal `json:"principals,omitempty"` | ||
Actions []string `json:"actions,omitempty"` | ||
FilterType string `json:"filterType,omitempty"` | ||
StartTime int64 `json:"startTime,omitempty"` | ||
EndTime int64 `json:"endTime,omitempty"` | ||
} | ||
|
||
type AuditOutput[T any] struct { | ||
Status string `json:"status,omitempty"` | ||
Data AuditOutputData[T] `json:"data,omitempty"` | ||
} | ||
|
||
type AuditOutputData[T any] struct { | ||
PageItemCount int `json:"pageItemCount,omitempty"` | ||
PageSize int `json:"pageSize,omitempty"` | ||
Content []T `json:"content,omitempty"` | ||
PageIndex int `json:"pageIndex,omitempty"` | ||
HasNext bool `json:"hasNext,omitempty"` | ||
PageToken string `json:"pageToken,omitempty"` | ||
TotalItems int `json:totalItems, omitempty` | ||
TotalPages int `json:totalPages, omitempty` | ||
} | ||
|
||
type AuditListItem struct { | ||
AuditID string `json:"auditId,omitempty"` | ||
InsertId string `json:"insertId,omitempty"` | ||
Resource AuditResource `json:"resource,omitempty"` | ||
Action string `json:"action,omitempty"` | ||
Module string `json:"module,omitempty"` | ||
Timestamp int64 `json:"timestamp,omitempty"` | ||
AuthenticationInfo AuditAuthenticationInfo `json:"authenticationInfo,omitempty"` | ||
ResourceScope AuditResourceScope `json:"resourceScope,omitempty"` | ||
} | ||
|
||
type AuditResource struct { | ||
Type string `json:"type"` | ||
Identifier string `json:"identifier"` | ||
Labels AuditResourceLabels `json:"labels,omitempty"` | ||
} | ||
|
||
type AuditResourceLabels struct { | ||
ResourceName string `json:"resourceName,omitempty"` | ||
} | ||
|
||
type AuditAuthenticationInfo struct { | ||
Principal AuditPrincipal `json:"principal"` | ||
Labels AuditAuthenticationInfoLabels `json:"labels,omitempty"` | ||
} | ||
|
||
type AuditAuthenticationInfoLabels struct { | ||
UserID string `json:"userId,omitempty"` | ||
Username string `json:"username,omitempty"` | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
package harness | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"math" | ||
"time" | ||
|
||
"github.com/harness/harness-mcp/client" | ||
"github.com/harness/harness-mcp/cmd/harness-mcp-server/config" | ||
"github.com/mark3labs/mcp-go/mcp" | ||
"github.com/mark3labs/mcp-go/server" | ||
) | ||
|
||
const ( | ||
minPage = 0 | ||
maxPage = 1000 | ||
minSize = 1 | ||
maxSize = 1000 | ||
) | ||
|
||
// ListAuditsOfUser creates a tool for listing the audit trail. | ||
func ListUserAuditTrailTool(config *config.Config, auditClient *client.AuditService) (tool mcp.Tool, handler server.ToolHandlerFunc) { | ||
return mcp.NewTool("list_user_audits", | ||
mcp.WithDescription("List the audit trail of the user."), | ||
mcp.WithString("user_id", | ||
mcp.Required(), | ||
mcp.Description("The user id used to retrieve the audit trail."), | ||
), | ||
mcp.WithNumber("start_time", | ||
mcp.Description("Optional start time in milliseconds"), | ||
mcp.DefaultNumber(0), | ||
), | ||
mcp.WithNumber("end_time", | ||
mcp.Description("Optional end time in milliseconds"), | ||
mcp.DefaultNumber(float64(time.Now().UnixMilli())), | ||
), | ||
WithScope(config, true), | ||
WithPagination(), | ||
), | ||
func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { | ||
userID, err := requiredParam[string](request, "user_id") | ||
if err != nil { | ||
return mcp.NewToolResultError(err.Error()), nil | ||
} | ||
|
||
scope, err := fetchScope(config, request, true) | ||
if err != nil { | ||
return mcp.NewToolResultError(err.Error()), nil | ||
} | ||
|
||
page, size, err := fetchPagination(request) | ||
if err != nil { | ||
return mcp.NewToolResultError(err.Error()), nil | ||
} | ||
|
||
page = int(math.Min(math.Max(float64(page), float64(minPage)), float64(maxPage))) | ||
size = int(math.Min(math.Max(float64(size), float64(minSize)), float64(maxSize))) | ||
|
||
startTime, _ := OptionalParam[int64](request, "start_time") | ||
endTime, _ := OptionalParam[int64](request, "end_time") | ||
|
||
data, err := auditClient.ListUserAuditTrail(ctx, scope, userID, page, size, startTime, endTime, nil) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to list the audit logs: %w", err) | ||
} | ||
|
||
r, err := json.Marshal(data) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to marshal the audit logs: %w", err) | ||
} | ||
|
||
return mcp.NewToolResultText(string(r)), nil | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
<audits> | ||
|
||
### 1. Audit Search Logic | ||
|
||
- When the user requests a specific audit or action **without specifying a page number or size**: | ||
- Use the default page size. | ||
- If no matching audit is found, increment the page size by 10 and continue searching. | ||
- Before continuing with further searches, ask the user for permission to keep checking. | ||
|
||
--- | ||
|
||
### 2. Output Formatting | ||
|
||
- For all audit outputs: | ||
- Provide results in **both JSON format and tabular format**. | ||
- Ensure every entry includes timestamps, unless the user specifically requests to exclude certain entries. | ||
|
||
--- | ||
|
||
### 3. Date to Unix Milliseconds Conversion | ||
|
||
- When fetching audits with a filter for start time or end time, or when converting any date to a Unix milliseconds timestamp: | ||
1. **Parse the prompt** to extract: | ||
- Year, month, day, and hour. | ||
- If minutes, seconds, or nanoseconds are not provided, default them to 0. | ||
2. **Use the following Go code template** to perform the conversion: | ||
```go | ||
loc, _ := time.LoadLocation({location}) | ||
t := time.Date({year}, time.{month}, {day}, {hour}, {minute}, {second}, {nanosecond}, loc) | ||
``` | ||
- Replace `{location}` with the value provided by the user ("Asia/Kolkata" or "UTC"). | ||
- Replace other placeholders with the extracted date/time values. | ||
3. **Important:** | ||
- Do **not** adjust the time for any location; use the time as given for the specified location. | ||
- Only use the location for the `{location}` parameter in the code. | ||
|
||
- **Location Selection:** | ||
- Ask the user to specify the location. | ||
- Available options: `"Asia/Kolkata"`, `"UTC"`. | ||
|
||
--- | ||
|
||
### 4. Go time.Date Function Reference | ||
|
||
- The format for the Go `time.Date` function is: | ||
```go | ||
time.Date( | ||
year int, | ||
month time.Month, | ||
day int, | ||
hour int, | ||
minute int, | ||
second int, | ||
nanosecond int, | ||
location *time.Location, | ||
) | ||
``` |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Audits are only available at account and org level. Is project needed for filtering ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This needs to be mentioned inside the scope field as mentioned in the API Documentation.